text
stringlengths
1
1.05M
gdt_start: ; don't remove the labels, they're needed to compute sizes and jumps ; the GDT starts with a null 8-byte dd 0x0 ; 4 byte dd 0x0 ; 4 byte ; GDT for code segment. base = 0x00000000, length = 0xfffff ; for flags, refer to os-dev.pdf document, page 36 gdt_code: dw 0xffff ; segment length, bits 0-15 dw 0x0 ; segment base, bits 0-15 db 0x0 ; segment base, bits 16-23 db 10011010b ; flags (8 bits) db 11001111b ; flags (4 bits) + segment length, bits 16-19 db 0x0 ; segment base, bits 24-31 ; GDT for data segment. base and length identical to code segment ; some flags changed, again, refer to os-dev.pdf gdt_data: dw 0xffff dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 gdt_end: ; GDT descriptor gdt_descriptor: dw gdt_end - gdt_start - 1 ; size (16 bit), always one less of its true size ; why one less? 😂 dd gdt_start ; address (32 bit) ; define some constants for later use CODE_SEG equ gdt_code - gdt_start DATA_SEG equ gdt_data - gdt_start
;/*! ; @file ; ; @brief BvsGetPhysBuf DOS wrapper ; ; (c) osFree Project 2021, <http://www.osFree.org> ; for licence see licence.txt in root directory, or project website ; ; This is Family API implementation for DOS, used with BIND tools ; to link required API ; ; @author Yuri Prokushev (yuri.prokushev@gmail.com) ; ;*/ .8086 ; Helpers INCLUDE HELPERS.INC INCLUDE DOS.INC INCLUDE BSEERR.INC _TEXT SEGMENT BYTE PUBLIC 'CODE' USE16 @BVSPROLOG BVSGETBUF VIOHANDLE DW ? ; SLength DD ? ; LVBPtr DD ? ; @BVSSTART BVSGETBUF XOR AX,AX ; ALL IS OK EXIT: @BVSEPILOG BVSGETBUF _TEXT ENDS END
//////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Southampton University 1999-2004 // (c) Andy Rushton 2004 onwards // License: BSD License, see ../docs/license.html // Contains all the platform-specific socket handling used by the TCP and UDP classes // TODO - any conversion required to support IPv6 //////////////////////////////////////////////////////////////////////////////// #include "ip_sockets.hpp" #include "dprintf.hpp" #include <string.h> #ifdef MSWINDOWS // Windoze-specific includes #include <winsock2.h> #define ERRNO WSAGetLastError() #define HERRNO WSAGetLastError() #define IOCTL ioctlsocket #define CLOSE closesocket #define SHUT_RDWR SD_BOTH #define SOCKLEN_T int #define SEND_FLAGS 0 // on Windows, these options have a different prefix but the same function as on Unix #define INPROGRESS WSAEINPROGRESS #define WOULDBLOCK WSAEWOULDBLOCK #define CONNRESET WSAECONNRESET #else // Generic Unix includes // fix for older versions of Darwin? #define _BSD_SOCKLEN_T_ int #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/time.h> #include <netinet/in.h> #include <errno.h> #include <netdb.h> #include <unistd.h> #define INVALID_SOCKET -1 #define ERRNO errno #define HERRNO h_errno #define SOCKET int #define SOCKET_ERROR -1 #define IOCTL ::ioctl #define CLOSE ::close #define SOCKLEN_T socklen_t #ifdef __APPLE__ // fix from IngwiePhoenix for OSX // https://github.com/Deskshell-Core/PhoenixEngine #define SEND_FLAGS SO_NOSIGPIPE #else #define SEND_FLAGS MSG_NOSIGNAL #endif #define INPROGRESS EINPROGRESS #define WOULDBLOCK EWOULDBLOCK #define CONNRESET ECONNRESET #ifdef SOLARIS // Sun put some definitions in a different place #include <sys/filio.h> #endif #endif //////////////////////////////////////////////////////////////////////////////// namespace stlplus { //////////////////////////////////////////////////////////////////////////////// // Utilities // get an operating-system error message given an error code static std::string error_string(int error) { std::string result = "error " + dformat("%d",error); #ifdef MSWINDOWS char* message = 0; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // "User default language" (LPTSTR)&message, 0,0); if (message) { result = message; LocalFree(message); } // the error message is for some perverse reason newline terminated - remove this if (result[result.size()-1] == '\n') result.erase(result.end()-1); if (result[result.size()-1] == '\r') result.erase(result.end()-1); #else char* message = strerror(error); if (message && message[0]) result = message; #endif return result; } // convert address:port into a sockaddr static void convert_address(unsigned long address, unsigned short port, sockaddr& sa) { sa.sa_family = AF_INET; unsigned short network_port = htons(port); memcpy(&sa.sa_data[0], &network_port, sizeof(network_port)); unsigned long network_address = htonl(address); memcpy(&sa.sa_data[2], &network_address, sizeof(network_address)); } // // convert host:port into a sockaddr // static void convert_host(hostent& host, unsigned short port, sockaddr& sa) // { // sa.sa_family = host.h_addrtype; // unsigned short network_port = htons(port); // memcpy(&sa.sa_data[0], &network_port, sizeof(network_port)); // memcpy(&sa.sa_data[2], host.h_addr, host.h_length); // } // convert sockaddr to address:port static void convert_sockaddr(const sockaddr& sa, unsigned long& address, unsigned short& port) { unsigned short network_port = 0; memcpy(&network_port, &sa.sa_data[0], sizeof(network_port)); port = ntohs(network_port); unsigned long network_address = 0; memcpy(&network_address, &sa.sa_data[2], sizeof(network_address)); address = ntohl(network_address); } //////////////////////////////////////////////////////////////////////////////// // Initialisation // Windows requires that Winsock is initialised before use and closed after // These routines initialise once on first use and close on the destruction of the last object using it // on non-windows platforms, I still increment/decrement the sockets count variable for diagnostic purposes static int sockets_count = 0; static int sockets_init(void) { int error = 0; if (sockets_count++ == 0) { #ifdef MSWINDOWS WSAData winsock_info; // request Winsock 2.0 or higher error = WSAStartup(MAKEWORD(2,0),&winsock_info); #endif } return error; } static int sockets_close(void) { int error = 0; if (--sockets_count == 0) { #ifdef MSWINDOWS if (WSACleanup() == SOCKET_ERROR) error = ERRNO; #endif } return error; } //////////////////////////////////////////////////////////////////////////////// // Socket Implementation - common code to manipulate a TCP socket class IP_socket_internals { private: IP_socket_type m_type; SOCKET m_socket; unsigned long m_remote_address; unsigned short m_remote_port; mutable int m_error; mutable std::string m_message; unsigned m_count; // disable copying of the internals IP_socket_internals(const IP_socket_internals&); IP_socket_internals& operator=(const IP_socket_internals&); public: //////////////////////////////////////////////////////////////////////////// // PIMPL alias counting void increment(void) { ++m_count; } bool decrement(void) { --m_count; return m_count == 0; } //////////////////////////////////////////////////////////////////////////// // constructors/destructors // construct an invalid socket IP_socket_internals(void) : m_type(undefined_socket_type), m_socket(INVALID_SOCKET), m_error(0), m_count(1) { set_error(sockets_init()); } // close on destroy ~IP_socket_internals(void) { close(); set_error(sockets_close()); } //////////////////////////////////////////////////////////////////////////// // initialisation, connection bool initialised(void) const { return m_socket != INVALID_SOCKET; } // attach this object to a pre-opened socket bool set(SOCKET socket, unsigned long remote_address, unsigned short remote_port) { if (initialised()) close(); clear_error(); m_socket = socket; m_remote_address = remote_address; m_remote_port = remote_port; return true; } // create a raw socket attached to this object bool initialise(IP_socket_type type) { if (initialised()) close(); clear_error(); if ((type != TCP) && (type != UDP)) { set_error(-1, "Illegal socket type"); return false; } // create an anonymous socket m_socket = ::socket(AF_INET, ((type == TCP) ? SOCK_STREAM : SOCK_DGRAM), 0); if (m_socket == INVALID_SOCKET) { set_error(ERRNO); close(); return false; } // record the type on success only m_type = type; // set the socket into non-blocking mode unsigned long nonblocking = 1; if (IOCTL(m_socket, FIONBIO, &nonblocking) == SOCKET_ERROR) { set_error(ERRNO); return false; } return true; } // function for performing IP lookup (i.e. gethostbyname) // could be standalone but making it a member means that it can use the socket's error handler // - remote_address: IP name or number // - returns the IP address as a number - zero if there's an error unsigned long ip_lookup(const std::string& remote_address) { unsigned long result = 0; // Lookup the IP address to convert it into a host record // this DOES lookup IP address names as well (not according to MS help !!) // TODO - convert this to use ::getaddrinfo - ::gethostbyname is deprecated hostent* host_info = ::gethostbyname(remote_address.c_str()); if (!host_info) { set_error(HERRNO); return 0; } // extract the address from the host info unsigned long network_address = 0; memcpy(&network_address, host_info->h_addr, host_info->h_length); result = ntohl(network_address); return result; } // tests whether a socket is ready for communication bool select(bool readable, bool writeable, unsigned wait) { if (!initialised()) return false; // set up the readable set fd_set readable_set; fd_set* readable_set_ptr = 0; if (readable) { FD_ZERO(&readable_set); FD_SET(m_socket,&readable_set); readable_set_ptr = &readable_set; } // set up the writeable set fd_set writeable_set; fd_set* writeable_set_ptr = 0; if (writeable) { FD_ZERO(&writeable_set); FD_SET(m_socket,&writeable_set); writeable_set_ptr = &writeable_set; } // TODO - check the error set and lookup the error? fd_set* error_set_ptr = 0; // set up the timout value // Note: a null pointer implements a blocking select // a pointer to a zero value implements a zero-wait poll // a pointer to a positive value implements a poll with a timeout // I currently only implement polling with timeout which may be zero - no blocking timeval timeout; timeval* timeout_ptr = 0; timeout.tv_sec = wait/1000000; timeout.tv_usec = wait%1000000; timeout_ptr = &timeout; // now test the socket int select_result = ::select(m_socket+1, readable_set_ptr, writeable_set_ptr, error_set_ptr, timeout_ptr); switch(select_result) { case SOCKET_ERROR: // select failed with an error - trap the error set_error(ERRNO); return false; case 0: // timeout exceeded without a connection appearing return false; default: // at least one connection is pending // TODO - do we need to do the extra socket options checking on Posix? // TODO - does this connect in any way to the error_set above? return true; } } // bind the socket to a port so that it can receive from specific address bool bind(unsigned long remote_address, unsigned short local_port) { if (!initialised()) return false; // name the socket and bind it to a port - this is a requirement for a server sockaddr server; convert_address(INADDR_ANY, local_port, server); if (::bind(m_socket, &server, sizeof(server)) == SOCKET_ERROR) { set_error(ERRNO); close(); return false; } return true; } // bind the socket to a port so that it can receive from any address bool bind_any(unsigned short local_port) { return bind(INADDR_ANY, local_port); } // set this socket up to be a listening port // must have been bound to a local port already // - length of backlog queue to manage - may be zero // - returns success status bool listen(unsigned short queue) { if (!initialised()) return false; // set the port to listen for incoming connections if (::listen(m_socket, (int)queue) == SOCKET_ERROR) { set_error(ERRNO); close(); return false; } return true; } // test whether there's an incoming connection on the socket // only applicable if it has been set up as a listening port bool accept_ready(unsigned wait) { // the test for a connection being ready is the same as the test for whether the socket is readable // see documentation for select return select(true, false, wait); } // accept a connection on the socket // only applicable if it has been set up as a listening port // - returns socket filled in with the accepted connection's details - or with the error fields set IP_socket accept(void) { if (!initialised()) return IP_socket(); IP_socket result; // accept the connection, at the same time getting the address of the connecting client sockaddr saddress; SOCKLEN_T saddress_length = sizeof(saddress); SOCKET socket = ::accept(m_socket, &saddress, &saddress_length); if (socket == INVALID_SOCKET) { // only set the result socket with an error result.m_impl->set_error(ERRNO); return result; } // extract the contents of the address unsigned long remote_address = 0; unsigned short remote_port = 0; convert_sockaddr(saddress, remote_address, remote_port); result.m_impl->set(socket, remote_address, remote_port); return result; } // client connect to a server // - remote_address: IP number of remote address to connect to // - remote_port: port to connect to bool connect(unsigned long remote_address, unsigned short remote_port) { if (!initialised()) return false; // fill in the connection data structure sockaddr connect_data; convert_address(remote_address, remote_port, connect_data); // connect binds the socket to a local address // if connectionless it simply sets the default remote address // if connectioned it makes the connection if (::connect(m_socket, &connect_data, sizeof(connect_data)) == SOCKET_ERROR) { // the socket is non-blocking, so connect will almost certainly fail with INPROGRESS which is not an error // only catch real errors int error = ERRNO; if (error != INPROGRESS && error != WOULDBLOCK) { set_error(error); return false; } } // extract the remote connection details for local storage convert_sockaddr(connect_data, m_remote_address, m_remote_port); return true; } // test whether a socket is connected and ready to communicate bool connected(unsigned wait) { if (!initialised()) return false; // Gnu/Linux and Windows docs say test with select for whether socket is // writable. However, a problem has been reported with Gnu/Linux whereby // the OS will report a socket as writable when it isn't // first use the select method if (!select(false, true, wait)) return false; #ifdef MSWINDOWS // Windows needs no further processing - select method works return true; #else // Posix version needs further checking using the socket options // http://linux.die.net/man/2/connect see description of EINPROGRESS // DJDM: socket has returned INPROGRESS on the first attempt at connection // it has also returned that it can be written to // we must now ask it if it has actually connected - using getsockopt int error = 0; socklen_t serror = sizeof(int); if (::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, &error, &serror) == 0) // handle the error value - the EISCONN error actually means that the socket has connected (so no error then) if (!error || error == EISCONN) return true; return false; #endif } bool close(void) { bool result = true; if (initialised()) { if (shutdown(m_socket,SHUT_RDWR) == SOCKET_ERROR) { set_error(ERRNO); result = false; } if (CLOSE(m_socket) == SOCKET_ERROR) { set_error(ERRNO); result = false; } } m_socket = INVALID_SOCKET; m_remote_address = 0; m_remote_port = 0; return result; } //////////////////////////////////////////////////////////////////////////// // sending/receiving bool send_ready(unsigned wait) { // determines whether the socket is ready to send by testing whether it is writable return select(false, true, wait); } bool send (std::string& data) { if (!initialised()) return false; // send the data - this will never block but may not send all the data int bytes = ::send(m_socket, data.c_str(), (int)data.size(), SEND_FLAGS); if (bytes == SOCKET_ERROR) { set_error(ERRNO); return false; } // remove the sent bytes from the data buffer so that the buffer represents the data still to be sent data.erase(0,bytes); return true; } bool send_packet(std::string& data, unsigned long address = 0, unsigned short port = 0) { if (!initialised()) return false; // if no address specified, rely on the socket having been connected (can I test this?) // so use the standard send, otherwise use the sendto function int bytes = 0; if (!address) { bytes = ::send(m_socket, data.c_str(), (int)data.size(), SEND_FLAGS); } else { sockaddr saddress; convert_address(address, port, saddress); bytes = ::sendto(m_socket, data.c_str(), (int)data.size(), SEND_FLAGS, &saddress, sizeof(saddress)); } if (bytes == SOCKET_ERROR) { set_error(ERRNO); return false; } // remove the sent bytes from the data buffer so that the buffer represents the data still to be sent data.erase(0,bytes); return true; } bool receive_ready(unsigned wait) { // determines whether the socket is ready to receive by testing whether it is readable return select(true, false, wait); } bool receive (std::string& data) { if (!initialised()) return false; // determine how much data is available to read unsigned long bytes = 0; if (IOCTL(m_socket, FIONREAD, &bytes) == SOCKET_ERROR) { set_error(ERRNO); return false; } // get the data up to the amount claimed to be present - this is non-blocking char* buffer = new char[bytes+1]; int read = ::recv(m_socket, buffer, bytes, 0); if (read == SOCKET_ERROR) { delete[] buffer; set_error(ERRNO); close(); return false; } if (read == 0) { // TODO - check whether this is an appropriate conditon to close the socket close(); } else { // this is binary data so copy the bytes including nulls data.append(buffer,read); } delete[] buffer; return true; } bool receive_packet(std::string& data, unsigned long& address, unsigned short& port) { if (!initialised()) return false; // determine how much data is available to read unsigned long bytes = 0; if (IOCTL(m_socket, FIONREAD, &bytes) == SOCKET_ERROR) { set_error(ERRNO); return false; } // get the data up to the amount claimed to be present - this is non-blocking // also get the sender's details char* buffer = new char[bytes+1]; sockaddr saddress; SOCKLEN_T saddress_length = sizeof(saddress); int read = ::recvfrom(m_socket, buffer, bytes, 0, &saddress, &saddress_length); if (read == SOCKET_ERROR) { // UDP connection reset means that a previous sent failed to deliver cos the address was unknown // this is NOT an error with the sending server socket, which IS still usable int error = ERRNO; if (error != CONNRESET) { delete[] buffer; set_error(error); close(); return false; } } // this is binary data so copy the bytes including nulls data.append(buffer,read); // also retrieve the sender's details convert_sockaddr(saddress, address, port); delete[] buffer; return true; } bool receive_packet(std::string& data) { // call the above and then discard the address details unsigned long address = 0; unsigned short port = 0; return receive_packet(data, address, port); } //////////////////////////////////////////////////////////////////////////// // informational IP_socket_type type(void) const { return m_type; } unsigned short local_port(void) const { if (!initialised()) return 0; sockaddr saddress; SOCKLEN_T saddress_length = sizeof(saddress); if (::getsockname(m_socket, &saddress, &saddress_length) != 0) { set_error(ERRNO); return 0; } unsigned long address = 0; unsigned short port = 0; convert_sockaddr(saddress, address, port); return port; } unsigned long remote_address(void) const { return m_remote_address; } unsigned short remote_port(void) const { return m_remote_port; } //////////////////////////////////////////////////////////////////////////// // error handling void set_error (int error, const char* message = 0) const { if (error != 0) { m_error = error; if (message && (message[0] != 0)) m_message = message; else m_message = error_string(error); } } int error(void) const { return m_error; } void clear_error (void) const { m_error = 0; m_message.erase(); } std::string message(void) const { return m_message; } }; //////////////////////////////////////////////////////////////////////////////// // Socket - common code to manipulate a socket // create an uninitialised socket IP_socket::IP_socket(void) : m_impl(new IP_socket_internals) { } // create an initialised socket // - type: create either a TCP or UDP socket - if neither, creates an uninitialised socket IP_socket::IP_socket(IP_socket_type type) : m_impl(new IP_socket_internals) { initialise(type); } // destroy the socket, closing it if open IP_socket::~IP_socket(void) { if (m_impl->decrement()) delete m_impl; } //////////////////////////////////////////////////////////////////////////// // copying is implemented as aliasing IP_socket::IP_socket(const IP_socket& right) : m_impl(0) { // make this an alias of right m_impl = right.m_impl; m_impl->increment(); } IP_socket& IP_socket::operator=(const IP_socket& right) { // make self-copy safe if (m_impl == right.m_impl) return *this; // first dealias the existing implementation if (m_impl->decrement()) delete m_impl; // now make this an alias of right m_impl = right.m_impl; m_impl->increment(); return *this; } //////////////////////////////////////////////////////////////////////////// // initialisation, connection // initialise the socket // - type: create either a TCP or UDP socket // - returns success status bool IP_socket::initialise(IP_socket_type type) { return m_impl->initialise(type); } // test whether this is an initialised socket // - returns whether this is initialised bool IP_socket::initialised(void) const { return m_impl->initialised(); } // close, i.e. disconnect the socket // - returns a success flag bool IP_socket::close(void) { return m_impl->close(); } // function for performing IP lookup (i.e. gethostbyname) // could be standalone but making it a member means that it can use the socket's error handler // - remote_address: IP name (stlplus.sourceforge.net) or dotted number (216.34.181.96) // - returns the IP address as a long integer - zero if there's an error unsigned long IP_socket::ip_lookup(const std::string& remote_address) { return m_impl->ip_lookup(remote_address); } // test whether a socket is ready to communicate // - readable: test whether socket is ready to read // - writeable: test whether a socket is ready to write // - timeout: if socket is not ready, time to wait before giving up - in micro-seconds - 0 means don't wait // returns false if not ready or error - use error() method to tell - true if ready bool IP_socket::select(bool readable, bool writeable, unsigned timeout) { return m_impl->select(readable, writeable, timeout); } // bind the socket to a port so that it can receive from specific address - typically used by a client // - remote_address: IP number of remote server to send/receive to/from // - local_port: port on local machine to bind to the address // - returns success flag bool IP_socket::bind(unsigned long remote_address, unsigned short local_port) { return m_impl->bind(remote_address, local_port); } // bind the socket to a port so that it can receive from any address - typically used by a server // - local_port: port on local machine to bind to the address // - returns success flag bool IP_socket::bind_any(unsigned short local_port) { return m_impl->bind_any(local_port); } // initialise a socket and set this socket up to be a listening port // - queue: length of backlog queue to manage - may be zero // - returns success status bool IP_socket::listen(unsigned short queue) { return m_impl->listen(queue); } // test for a connection on the object's socket - only applicable if it has been set up as a listening port // - returns true if a connection is ready to be accepted bool IP_socket::accept_ready(unsigned timeout) const { return m_impl->accept_ready(timeout); } // accept a connection on the object's socket - only applicable if it has been set up as a listening port // - returns the connection as a new socket IP_socket IP_socket::accept(void) { return m_impl->accept(); } // client connect to a server // - address: IP number already lookup up with ip_lookup // - port: port to connect to // - returns a success flag bool IP_socket::connect(unsigned long address, unsigned short port) { return m_impl->connect(address, port); } // test whether a socket is connected and ready to communicate, returns on successful connect or timeout // - timeout: how long to wait in microseconds if not connected yet // - returns success flag bool IP_socket::connected(unsigned timeout) { return m_impl->connected(timeout); } //////////////////////////////////////////////////////////////////////////// // sending/receiving // test whether a socket is connected and ready to send data, returns if ready or on timeout // - timeout: how long to wait in microseconds if not connected yet (blocking) // - returns status bool IP_socket::send_ready(unsigned timeout) { return m_impl->send_ready(timeout); } // send data through the socket - if the data is long only part of it may // be sent. The sent part is removed from the data, so the same string can // be sent again and again until it is empty. // - data: string containing data to be sent - any data successfully sent is removed // - returns success flag bool IP_socket::send (std::string& data) { return m_impl->send(data); } // send data through a connectionless (UDP) socket // the data will be sent as a single packet // - packet: string containing data to be sent - any data successfully sent is removed // - remote_address: address of the remote host to send to - optional if the socket has been connected to remote // - remote_port: port of the remote host to send to - optional if the socket has been connected to remote // - returns success flag bool IP_socket::send_packet(std::string& packet, unsigned long remote_address, unsigned short remote_port) { return m_impl->send_packet(packet, remote_address, remote_port); } // send data through a connectionless (UDP) socket // the data will be sent as a single packet // only works if the socket has been connected to remote // - packet: string containing data to be sent - any data successfully sent is removed // - returns success flag bool IP_socket::send_packet(std::string& packet) { return m_impl->send_packet(packet); } // test whether a socket is connected and ready to receive data, returns if ready or on timeout // - timeout: how long to wait in microseconds if not connected yet (blocking) // - returns status bool IP_socket::receive_ready(unsigned timeout) { return m_impl->receive_ready(timeout); } // receive data through a connection-based (TCP) socket // if the data is long only part of it may be received. The received data // is appended to the string, building it up in stages, so the same string // can be received again and again until all information has been // received. // - data: string receiving data from socket - any data successfully received is appended // - returns success flag bool IP_socket::receive (std::string& data) { return m_impl->receive(data); } // receive data through a connectionless (UDP) socket // - packet: string receiving data from socket - any data successfully received is appended // - remote_address: returns the address of the remote host received from // - remote_port: returns the port of the remote host received from // - returns success flag bool IP_socket::receive_packet(std::string& packet, unsigned long& remote_address, unsigned short& remote_port) { return m_impl->receive_packet(packet, remote_address, remote_port); } // variant of above which does not give back the address and port of the sender // receive data through a connectionless (UDP) socket // - packet: string receiving data from socket - any data successfully received is appended // - returns success flag bool IP_socket::receive_packet(std::string& packet) { return m_impl->receive_packet(packet); } //////////////////////////////////////////////////////////////////////////// // informational IP_socket_type IP_socket::type(void) const { return m_impl->type(); } unsigned short IP_socket::local_port(void) const { return m_impl->local_port(); } unsigned long IP_socket::remote_address(void) const { return m_impl->remote_address(); } unsigned short IP_socket::remote_port(void) const { return m_impl->remote_port(); } //////////////////////////////////////////////////////////////////////////// // error handling void IP_socket::set_error (int error, const std::string& message) const { m_impl->set_error(error, message.c_str()); } void IP_socket::clear_error (void) const { m_impl->clear_error(); } int IP_socket::error(void) const { return m_impl->error(); } std::string IP_socket::message(void) const { return m_impl->message(); } //////////////////////////////////////////////////////////////////////////////// } // end namespace stlplus
; ; Sharp OZ family functions ; ; ported from the OZ-7xx SDK by by Alexander R. Pruss ; by Stefano Bodrato - Oct. 2003 ; ; ; gfx functions ; ; int ozputs(int x, int y, char *string); ; ; ------ ; $Id: ozputs.asm,v 1.4 2016-06-28 14:48:17 dom Exp $ ; SECTION smc_clib PUBLIC ozputs PUBLIC _ozputs PUBLIC ozputsgetend PUBLIC _ozputsgetend EXTERN ozdetectmodel EXTERN restore_a000 EXTERN ozfontpointers EXTERN ozmodel EXTERN ozactivepage PUBLIC s_end_s_pointer EXTERN LowerFontPage1 EXTERN LowerFontPage2 EXTERN HigherFontPage1 EXTERN HigherFontPage2 EXTERN ScrCharSet ;; strlen equ 7f0ch ;; DisplayStringAt equ 7f4ch ;; Portable if ScrCharSet is portable ;; ozputsgetend: _ozputsgetend: ;ld hl,0 ;; self-mod defb 33 s_end_s_pointer: defw 0 ; $end$pointer equ $-2 ;; ret DoInit: ld a,1 ld (init),a ld a,(ozmodel) xor 0ffh call z,ozdetectmodel ld a,(ozmodel) and 4 jr z,DidInit ;; not multilingual, so all is OK ld a,1eh ld (LowerFontPage1),a ld (LowerFontPage2),a inc a ld (HigherFontPage1),a ld (HigherFontPage2),a jr DidInit ; int ozputs(int x, int y, char *string); ozputs: _ozputs: ld a,(init) or a jr z,DoInit DidInit: ;;;yyll001122 push iy ld iy,2 add iy,sp push ix exx ld de,(ozactivepage) ;ld l,(iy+6) ;ld h,(iy+7) ; address of string ld l,(iy+2) ld h,(iy+3) ; address of string exx ld a,(ScrCharSet) and 7 add a,a ld d,0 ld e,a ld hl,ozfontpointers add hl,de ld e,(hl) inc hl ld d,(hl) push de pop ix ld a,(ix+0) ld (font_page+1),a ld a,(ix+1) ld (font_page_hi+1),a ld l,(ix+2) ld h,(ix+3) ld (font_len_offset+1),hl ld l,(ix+4) ld h,(ix+5) ld (font_offset+1),hl ld (font_offset_double+1),hl ld e,(ix+6) ;; height ld a,(ix+7) ;; charset mask ld (charset_mask+1),a ;ld a,(iy+5) ld a,(iy+5) or a jp nz,LengthOnly ld a,80 ;ld c,(iy+4) ld c,(iy+4) sub c ;; number of rows available jp c,LengthOnly jp z,LengthOnly cp e jp nc,HeightOK ld e,a HeightOK: ld a,e ld (height+1),a ld (height_double+2),a ;ld l,(iy+4) ld l,(iy+4) ld h,0 add hl,hl ld c,l ld b,h ; bc=2*y add hl,hl ; hl=4*y add hl,hl ; hl=8*y add hl,hl ; hl=16*y add hl,hl ; hl=32*y sbc hl,bc ; hl=30*y ld bc,0a000h add hl,bc push hl pop ix ; ix=screen-offset for y ;ld c,(iy+2) ; x-position ;ld b,(iy+3) ld c,(iy+6) ; x-position ld b,(iy+7) exx DoPrintLoop: ld a,(hl) ;; get character from string or a jp z,done charset_mask: and 0ffh ;charset_mask equ $-1 exx push bc ;; x-pos font_len_offset: ld hl,0000h ;; self modifying code ;font_len_offset equ $-2 ld c,a ld b,0 add hl,bc add hl,bc add hl,bc push hl pop iy ;; iy=font character record position ld a,(font_page+1) out (3),a ld a,(font_page_hi+1) out (4),a ld a,(hl) ; width ld l,a ld h,b ; h=0 as b=0 still pop bc ; x-position push bc ld e,c add hl,bc ld (EndXPos+1),hl ld bc,240 sbc hl,bc jp nc,DonePop2 cp 9 ; is width more than 8 jp nc,DoubleWidth ld l,a ; width ld h,b ; h=0 as b=0 still ;; hl=width ld bc,Masks add hl,bc ld d,(hl) ; mask for correct width ld a,e ; low byte of x-position ld e,0 and 7 ld (low_nibble+1),a jr z,EndRotMask ld b,a RotRightMask: rl d ;; carry is clear because of "or a" and "dec a" rl e djnz RotRightMask EndRotMask: ld a,d cpl ld (mask1+1),a ld a,e cpl ld (mask2+1),a ld l,(iy+1) ;; font position ld h,(iy+2) font_offset: ld bc,0000h ;; self-modifying code ;font_offset equ $-2 ;; add hl,bc ;; hl=position of font data for character push hl pop iy ;; iy=font data $end$pointer pop bc ;; x-position of start srl c srl c srl c ld b,0 push ix pop hl ;; hl=screen position add hl,bc height: ld c,00 ;; character row counter (self-modifying) ;height equ $-1 ;; InnerCharLoop: low_nibble: ld b,00 ;; self-modifying code ;low_nibble equ $-1 ;; font_page: ld a,0 ;; self-modifying code ;font_page equ $-1 out (3),a font_page_hi: ld a,0 ;font_page_hi equ $-1 out (4),a ld e,0 ld d,(iy+0) exx ld a,e out (3),a ld a,d out (4),a exx ld a,b or a jr z,NoCharacterShift ShiftByte: rl d rl e djnz ShiftByte NoCharacterShift: ld a,(hl) ;; get from screen mask1: and 00 ;; self-modifying code ;mask1 equ $-1 ;; or d ld (hl),a inc hl ld a,(hl) mask2: and 00 ;; self-modifying code ;mask2 equ $-1 ;; or e ld (hl),a ld de,29 add hl,de inc iy dec c jp nz,InnerCharLoop EndOfCharPut: EndXPos: ld bc,0000 ;; self-modifying code ;EndXPos equ $-2 ;; exx inc hl ld a,7 ;; restore original page out (3),a ld a,4 out (4),a jp DoPrintLoop done: ld (s_end_s_pointer),hl exx ld l,c ld h,b cleanup_page: pop ix pop iy jp restore_a000 DonePop2: pop hl ; x position exx ld (s_end_s_pointer),hl exx jr cleanup_page DoubleWidth: sub 8 ld l,a ; width-8 ld h,b ; h=0 as b=0 still ;; hl=width ld bc,Masks add hl,bc ld a,e ; low byte of x-position and 7 ld (low_nibble_double+1),a ld d,0ffh ld e,(hl) ; mask for correct width ld c,0 jr z,EndRotMask_double ld b,a RotRightMask_double: rl d ;; carry is clear because of "or a" and "dec a" rl e rl c djnz RotRightMask_double EndRotMask_double: ld a,d cpl ld (mask1_double+1),a ld a,e cpl ld (mask2_double+1),a ld a,c cpl ld (mask3_double+1),a ld l,(iy+1) ;; font position ld h,(iy+2) font_offset_double: ld bc,0000h ;; self-modifying code ;font_offset_double equ $-2 ;; add hl,bc ;; hl=position of font data for character push hl pop iy ;; iy=font data $end$pointer pop bc ;; x-position of start srl c srl c srl c ld b,0 push ix pop hl ;; hl=screen position add hl,bc push ix height_double: ;undoc_ix ;ld l,00 ;; ld ixl,00 : character row counter (self-modifying) ld ixl,0 ;height_double equ $-1 ;; InnerCharLoop_double: low_nibble_double: ld b,00 ;; self-modifying code ;low_nibble_double equ $-1 ;; ld a,(font_page+1) out (3),a ld a,(font_page_hi+1) out (4),a ld d,(iy+0) inc iy ld e,(iy+0) ld c,0 exx ld a,e out (3),a ld a,d out (4),a exx ld a,b or a jr z,NoCharacterShift_double ShiftByte_double: rl d rl e rl c djnz ShiftByte_double NoCharacterShift_double: ld a,(hl) ;; get from screen mask1_double: and 00 ;; self-modifying code ;; should be AND ;mask1_double equ $-1 ;; or d ld (hl),a inc hl ld a,(hl) mask2_double: and 00 ;; self-modifying code ;; should be AND ;mask2_double equ $-1 ;; or e ld (hl),a inc hl ld a,(hl) mask3_double: and 00 ;; self-modifying code ;; should be AND ;mask3_double equ $-1 ;; or c ld (hl),a ld de,28 add hl,de inc iy ;undoc_ix ;dec l dec ixl jp nz,InnerCharLoop_double pop ix jp EndOfCharPut LengthOnly: exx push hl exx pop de ld c,(iy+2) ; x-position ld b,(iy+3) DoCountLoop: ld a,(de) ;; get character from string or a jr z,doneCounting push bc ;; x-pos ld hl,(font_len_offset) ld c,a ld b,0 add hl,bc add hl,bc add hl,bc ld a,(font_page+1) out (3),a ld a,(font_page_hi+1) out (4),a ld a,(hl) ; width ld l,a ld h,b ; h=0 as b=0 still pop bc ; x-position add hl,bc ld c,l ld b,h inc de ld a,7 out (3),a ld a,4 out (4),a jp DoCountLoop doneCounting: ld l,c ld h,b jp cleanup_page Masks: defb 1,3,7,15,31,63,127,255 init: defs 1
lev80 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 ; PF1 byte %00000000 byte %00000000 byte %00111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00111111 byte %00000000 ; PF2 byte %00000000 byte %00000000 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00000000 lev81 ; PF0 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %00000000 byte %00000000 ; PF1 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 ; PF2 byte %00000111 byte %00000111 byte %00000111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %00000000 byte %00000000 lev82 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 byte %10001000 ; PF1 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 ; PF2 byte %00000000 byte %00000000 byte %00000000 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %00000111 byte %00000111 byte %00000111 lev83 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 byte %00000000 ; PF1 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %01111111 byte %01111111 byte %01111111 ; PF2 byte %00000000 byte %00000000 byte %00000000 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 lev84 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 ; PF1 byte %01111111 byte %01111111 byte %01111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 ; PF2 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00011111 byte %00000000 byte %00000000 lev85 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 ; PF1 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 ; PF2 byte %00000000 byte %00000000 byte %00000000 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %00000000 byte %00000000 lev86 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 ; PF1 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 ; PF2 byte %00000000 byte %00000000 byte %00000000 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %00000111 byte %00000111 lev87 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 ; PF1 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 byte %00000000 ; PF2 byte %00000111 byte %00000111 byte %00000111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %00000000 byte %00000000 byte %00000000 lev88 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 byte %00000000 ; PF1 byte %01111111 byte %01111111 byte %01111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %11111111 byte %00000000 byte %00000000 byte %00000000 ; PF2 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00000000 byte %00000000 byte %00000000 lev89 ; PF0 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 byte %00000000 ; PF1 byte %00000000 byte %00000000 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 byte %01111111 ; PF2 byte %00000000 byte %00000000 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 byte %00001111 col89 byte $BA byte $44 byte $44 byte $BA byte $BA byte $BA ; Default colors col80 col81 col82 col83 col84 col85 col86 col87 col88 byte $BA byte $BA byte $BA byte $BA byte $BA byte $BA
SECTION code_fp_math32 PUBLIC l_f32_invf EXTERN m32_fsinv_fastcall defc l_f32_invf = m32_fsinv_fastcall
extern m7_ippsECCPSetStdSM2:function extern n8_ippsECCPSetStdSM2:function extern y8_ippsECCPSetStdSM2:function extern e9_ippsECCPSetStdSM2:function extern l9_ippsECCPSetStdSM2:function extern n0_ippsECCPSetStdSM2:function extern k0_ippsECCPSetStdSM2:function extern ippcpJumpIndexForMergedLibs extern ippcpSafeInit:function segment .data align 8 dq .Lin_ippsECCPSetStdSM2 .Larraddr_ippsECCPSetStdSM2: dq m7_ippsECCPSetStdSM2 dq n8_ippsECCPSetStdSM2 dq y8_ippsECCPSetStdSM2 dq e9_ippsECCPSetStdSM2 dq l9_ippsECCPSetStdSM2 dq n0_ippsECCPSetStdSM2 dq k0_ippsECCPSetStdSM2 segment .text global ippsECCPSetStdSM2:function (ippsECCPSetStdSM2.LEndippsECCPSetStdSM2 - ippsECCPSetStdSM2) .Lin_ippsECCPSetStdSM2: db 0xf3, 0x0f, 0x1e, 0xfa call ippcpSafeInit wrt ..plt align 16 ippsECCPSetStdSM2: db 0xf3, 0x0f, 0x1e, 0xfa mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc] movsxd rax, dword [rax] lea r11, [rel .Larraddr_ippsECCPSetStdSM2] mov r11, qword [r11+rax*8] jmp r11 .LEndippsECCPSetStdSM2:
; A093149: a(1) = 4; a(n) = (n^(n+1)+2*n-3)/(n-1) for n > 1. ; 4,9,42,343,3908,55989,960802,19173963,435848052,11111111113,313842837674,9726655034463,328114698808276,11966776581370173,469172025408063618,19676527011956855059,878942778254232811940,41660902667961039785745,2088331858752553232964202 add $0,1 mov $2,$0 lpb $0 sub $0,1 add $1,2 mul $1,$2 lpe div $1,2 add $1,3 mov $0,$1
; Low level interrupt/thread handling code for GeekOS. ; Copyright (c) 2001,2003,2004 David H. Hovemeyer <daveho@cs.umd.edu> ; Copyright (c) 2003,2014 Jeffrey K. Hollingsworth <hollings@cs.umd.edu> ; $Revision: 1.18 $ ; All rights reserved. ; This code may not be resdistributed without the permission of the copyright holders. ; This is 32 bit code to be linked into the kernel. ; It defines low level interrupt handler entry points that we'll use ; to populate the IDT. It also contains the interrupt handling ; and thread context switch code. %include "defs.asm" %include "symbol.asm" [BITS 32] ; ---------------------------------------------------------------------- ; Definitions ; ---------------------------------------------------------------------- ; This is the size of the Interrupt_State struct in int.h INTERRUPT_STATE_SIZE equ 64 ; Save registers prior to calling a handler function. ; This must be kept up to date with: ; - Interrupt_State struct in int.h ; - Setup_Kernel_Thread(), Setup_User_Thread() in kthread.c ; - REG_SKIP, EFLAGS_SKIP below (count of registers pushed * 4) ; - INTERRUPT_STATE_SIZE above (count of registers pushed * 4) %macro Save_Registers 0 push eax push ebx push ecx push edx push esi push edi push ebp push ds push es push fs push gs %endmacro ; Restore registers and clean up the stack after calling a handler function ; (i.e., just before we return from the interrupt via an iret instruction). %macro Restore_Registers 0 pop gs pop fs pop es pop ds pop ebp pop edi pop esi pop edx pop ecx pop ebx pop eax add esp, 8 ; skip int num and error code %endmacro ; Code to activate a new user context (if necessary), before returning ; to executing a thread. Should be called just before restoring ; registers (because the interrupt context is used). %macro Activate_User_Context 0 ; If the new thread has a user context which is not the current ; one, activate it. push esp ; Interrupt_State pointer Push_Current_Thread_PTR call Switch_To_User_Context add esp, 8 ; clear 2 arguments %endmacro ; Code to rearrange the stack to activate a signal handler %macro Process_Signal 1 ; Check if a signal is pending. If so, we need to ; rearrange the stack so that when the thread restarts ; it will enter the signal handler and then afterward ; return to its original spot push esp Push_Current_Thread_PTR call Check_Pending_Signal add esp, 8 cmp eax, dword 0 je %1 ; We have a pending signal, so we must arrange to ; call its signal handler ; push esp ; call Print_IS ; add esp, 4 push esp Push_Current_Thread_PTR call Setup_Frame add esp, 8 ; push esp ; call Print_IS ; add esp, 4 %endmacro ; Number of bytes between the top of the stack and ; the interrupt number after the general-purpose and segment ; registers have been saved. REG_SKIP equ (11*4) ; Number of bytes from top of the stack the the saved EFLAGS after ; GP and seg registers have been saved EFLAGS_SKIP equ (REG_SKIP + (4*4)) ; bit mask for Interrupt enable bit of EFLAGS EFLAGS_IF equ word 0x200 ; Template for entry point code for interrupts that have ; an explicit processor-generated error code. ; The argument is the interrupt number. %macro Int_With_Err 1 align 16 push dword %1 ; push interrupt number jmp Handle_Interrupt ; jump to common handler %endmacro ; Template for entry point code for interrupts that do not ; generate an explicit error code. We push a dummy error ; code on the stack, so the stack layout is the same ; for all interrupts. %macro Int_No_Err 1 align 16 push dword 0 ; fake error code push dword %1 ; push interrupt number jmp Handle_Interrupt ; jump to common handler %endmacro ; ---------------------------------------------------------------------- ; Symbol imports and exports ; ---------------------------------------------------------------------- IMPORT unlockKernel IMPORT lockKernel IMPORT kthreadLock ; to avoid preemption when the kthread spinlock is held. ; This symbol is defined in idt.c, and is a table of addresses ; of C handler functions for interrupts. IMPORT g_interruptTable ; Global variable pointing to context struct for current thread. IMPORT g_currentThreads ; Set to non-zero when we need to choose a new thread ; in the interrupt return code. IMPORT g_needReschedule ; Set to non-zero when preemption is disabled. IMPORT g_preemptionDisabled ; This is the function that returns the next runnable thread. IMPORT Get_Next_Runnable ; Function to put a thread on the run queue. IMPORT Make_Runnable ; Function to activate a new user context (if needed). IMPORT Switch_To_User_Context ; Function that checks if the current thread has a signal pending. IMPORT Check_Pending_Signal ; Function that sets up the stack frame to invoke a signal handler IMPORT Setup_Frame ;; Function to manipulate APIC IMPORT APIC_Write ; In case of error, just terminate. IMPORT Hardware_Shutdown ; Sizes of interrupt handler entry points for interrupts with ; and without error codes. The code in idt.c uses this ; information to infer the layout of the table of interrupt ; handler entry points, without needing a separate linker ; symbol for each one (which is quite tedious to type :-) EXPORT g_handlerSizeNoErr EXPORT g_handlerSizeErr ; Simple functions to load the IDTR, GDTR, and LDTR. EXPORT Load_IDTR EXPORT Load_GDTR EXPORT Load_LDTR ; Beginning and end of the table of interrupt entry points. EXPORT g_entryPointTableStart EXPORT g_entryPointTableEnd ; Thread context switch function. EXPORT Switch_To_Thread ; Return current value of eflags register. EXPORT Get_Current_EFLAGS ; Virtual memory support. EXPORT Enable_Paging EXPORT Set_PDBR EXPORT Get_PDBR EXPORT Flush_TLB ; Spin Lock EXPORT Spin_Lock_INTERNAL EXPORT Spin_Unlock_INTERNAL EXPORT Send_Timer_INT ; ---------------------------------------------------------------------- ; Code ; ---------------------------------------------------------------------- [SECTION .text] ; Load IDTR with 6-byte pointer whose address is passed as ; the parameter. align 8 Load_IDTR: mov eax, [esp+4] lidt [eax] ret ; Load the GDTR with 6-byte pointer whose address is ; passed as the parameter. Assumes that interrupts ; are disabled. align 8 Load_GDTR: mov eax, [esp+4] lgdt [eax] ; Reload segment registers mov ax, KERNEL_DS mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax jmp KERNEL_CS:.here .here: ret ; Load the LDT whose selector is passed as a parameter. align 8 Load_LDTR: mov eax, [esp+4] lldt ax ret ; ; Start paging ; load crt3 with the passed page directory pointer ; enable paging bit in cr2 ;; nspring - ecx is caller save, ebx is callee save. align 8 Enable_Paging: mov eax, [esp+4] mov cr3, eax mov eax, cr3 mov cr3, eax mov ecx, cr0 or ecx, 0x80000000 mov cr0, ecx ret ; ; Change PDBR ; load cr3 with the passed page directory pointer align 8 Set_PDBR: mov eax, [esp+4] mov cr3, eax ; mov eax, [esp+4] ; mov cr3, eax ret ; ; Get the current PDBR. ; This is useful for lazily switching address spaces; ; only switch if the new thread has a different address space. ; align 8 Get_PDBR: mov eax, cr3 ret ; ; Flush TLB - just need to re-load cr3 to force this to happen ; ; - XXXX do we need to shoot down the TLBs on other cores with an IPI?? ; - might need to just make sure we don't take pages from other processes, since the TLB clearing is currently ; only used to clear the TLB when we take page out a page from a process, need to ensure the TLB entry (if any) ; for it is cleared. When we start to have shared memory between cores, will need to look at a full shootdown ; strategy. ; align 8 Flush_TLB: mov eax, cr3 mov cr3, eax ret APIC_BASE equ 0xFEE00000 APIC_ID equ 0x20 ;; ;; eax = &g_currentThreads[Get_CPU_ID()]; ;; %macro Mov_EAX_Current_Thread_PTR 0 mov eax, [APIC_BASE+APIC_ID] ;; load id of local APC (which is cpuid) shr eax, 24-2 ;; id is in high 24 bits of register, but need id <<2 add eax, g_currentThreads %endmacro ;; eax = *( &g_currentThreads[Get_CPU_ID()] ) %macro Get_Current_Thread_To_EAX 0 Mov_EAX_Current_Thread_PTR mov eax, [eax] %endmacro %macro Set_Current_Thread_From_EBX 0 Mov_EAX_Current_Thread_PTR mov [eax], ebx %endmacro %macro Push_Current_Thread_PTR 0 Mov_EAX_Current_Thread_PTR push dword [eax] %endmacro %include "percpu.asm" ; Common interrupt handling code. ; Save registers, call C handler function, ; possibly choose a new thread to run, restore ; registers, return from the interrupt. align 8 Handle_Interrupt: ; macro defined above to push registers and create Interrupt_State Save_Registers ; Ensure that we're using the kernel data segment mov ax, KERNEL_DS mov ds, ax mov es, ax ; Get the address of the C handler function from the ; table of handler functions. mov eax, g_interruptTable ; get address of handler table mov esi, [esp+REG_SKIP] ; get interrupt number mov ebx, [eax+esi*4] ; get address of handler function test ebx,ebx ; if handler is null (ebx & ebx == 0), set ZF jz .bail_no_handler ; if ZF, halt for debugging. ; Call the handler. ; The argument passed is a pointer to an Interrupt_State struct, ; which describes the stack layout for all interrupts. push esp ; struct Interrupt_State * call ebx add esp, 4 ; clear 1 argument ; If preemption is disabled, then the current thread ; keeps running. mov ebx, [APIC_BASE+APIC_ID] ;; load id of local APC (which is cpuid) shr ebx, 24-2 ;; id is in high 24 bits of register, but need id <<2 cmp [g_preemptionDisabled+ebx], dword 0 jne .tramp_restore ;; nspring - check if kthreadLock is; if so, skip preemption. ;; this is a hack. it can help, but is not reliable (we are ;; not acquiring the lock, but another thread might. ;;; TODO: move this into eax to leave ebx untouched to simplify the needReschedule comparison. mov ebx, [kthreadLock] ;; the lock value at the front of the spinlock. jne .tramp_restore ; See if we need to choose a new thread to run. mov ebx, [APIC_BASE+APIC_ID] ;; load id of local APC (which is cpuid) shr ebx, 24-2 ;; id is in high 24 bits of register, but need id <<2 cmp [g_needReschedule+ebx], dword 0 je .tramp_restore ; Put current thread back on the run queue Push_Current_Thread_PTR call Make_Runnable add esp, 4 ; clear 1 argument ; Save stack pointer in current thread context, and ; clear numTicks field. Get_Current_Thread_To_EAX test eax,eax jne .ok jmp .bail_null_current_thread .tramp_restore: jmp .restore .bail_no_handler: call Hardware_Shutdown .ok: mov [eax+0], esp ; esp field mov [eax+4], dword 0 ; numTicks field ; Pick a new thread to run, and switch to its stack call Get_Next_Runnable mov ebx, eax ; save new thread into ebx test eax, eax ; possibly redundant setting of the flags. jne .ok2 jmp .bail_null_runnable_thread .ok2: Set_Current_Thread_From_EBX mov esp, [ebx+0] ; load esp from new thread ; Clear "need reschedule" flag mov ebx, [APIC_BASE+APIC_ID] ;; load id of local APC (which is cpuid) shr ebx, 24-2 ;; id is in high 24 bits of register, but need id <<2 mov [g_needReschedule+ebx], dword 0 .restore: ; Activate the user context, if necessary. Activate_User_Context Process_Signal .finish .finish: ; clear APIC Interrupt info mov [APIC_BASE+APIC_EOI], dword 0 mov eax, esp ; debug ns: get esp into a register that's dumped on exception. ; Restore registers Restore_Registers ; Return from the interrupt. iret .bail_null_current_thread: call Hardware_Shutdown .bail_null_runnable_thread: call Hardware_Shutdown ; ---------------------------------------------------------------------- ; Switch_To_Thread() ; Save context of currently executing thread, and activate ; the thread whose context object is passed as a parameter. ; ; Parameter: ; - ptr to Kernel_Thread whose state should be restored and made active ; ; Notes: ; Called with interrupts disabled. ; This must be kept up to date with definition of Kernel_Thread ; struct, in kthread.h. ; ---------------------------------------------------------------------- align 16 Switch_To_Thread: ; Modify the stack to allow a later return via an iret instruction. ; We start with a stack that looks like this: ; ; thread_ptr ; esp --> return addr ; ; We change it to look like this: ; ; thread_ptr ; eflags ; cs ; esp --> return addr push eax ; save eax mov eax, [esp+4] ; get return address mov [esp-4], eax ; move return addr down 8 bytes from orig loc add esp, 8 ; move stack ptr up pushfd ; put eflags where return address was mov eax, [esp-4] ; restore saved value of eax push dword KERNEL_CS ; push cs selector sub esp, 4 ; point stack ptr at return address ; Push fake error code and interrupt number push dword 0 push dword 0 ; Save general purpose registers. Save_Registers ; Save stack pointer in the thread context struct (at offset 0). Get_Current_Thread_To_EAX mov [eax+0], esp ; Clear numTicks field in thread context, since this ; thread is being suspended. mov [eax+4], dword 0 ; Load the pointer to the new thread context into eax. ; We skip over the Interrupt_State struct on the stack to ; get the parameter. mov eax, [esp+INTERRUPT_STATE_SIZE] ; Make the new thread current, and switch to its stack. mov ebx, eax Set_Current_Thread_From_EBX mov esp, [ebx+0] ; Activate the user context, if necessary. Activate_User_Context ; clear APIC Interrupt info mov [APIC_BASE+APIC_EOI], dword 0 Process_Signal .complete .complete: mov eax, esp ; debug ns; get esp into a register that is dumped if there's a trap. ; Restore general purpose and segment registers, and clear interrupt ; number and error code. Restore_Registers ; We'll return to the place where the thread was ; executing last. iret ; Return current contents of eflags register. align 16 Get_Current_EFLAGS: pushfd ; push eflags pop eax ; pop contents into eax ret lockops: dd 0 ;; nspring - ecx is caller save, ebx is callee save. ;; http://www.cs.virginia.edu/~evans/cs216/guides/x86.html Spin_Lock_INTERNAL: mov ecx, [esp+4] .still_locked_early: mov eax, [ecx] test eax, eax jnz .still_locked_early .seems_unlocked: mov eax, 1 xchg eax, [ecx] ; "lock" implicit for xchg. test eax, eax jnz Spin_Lock_INTERNAL inc dword [lockops] ret ;; nspring - ecx is caller save, ebx is callee save. ;; http://www.cs.virginia.edu/~evans/cs216/guides/x86.html Spin_Unlock_INTERNAL: mov ecx, [esp+4] mov eax, 0 xchg eax, [ecx] ret Send_Timer_INT: int 0h ret ; ---------------------------------------------------------------------- ; Generate interrupt-specific entry points for all interrupts. ; We also define symbols to indicate the extend of the table ; of entry points, and the size of individual entry points. ; ---------------------------------------------------------------------- align 16 g_entryPointTableStart: ; Handlers for processor-generated exceptions, as defined by ; Intel 486 manual. Int_No_Err 0 align 16 Before_No_Err: Int_No_Err 1 align 16 After_No_Err: Int_No_Err 2 ; FIXME: not described in 486 manual Int_No_Err 3 Int_No_Err 4 Int_No_Err 5 Int_No_Err 6 Int_No_Err 7 align 16 Before_Err: Int_With_Err 8 align 16 After_Err: Int_No_Err 9 ; FIXME: not described in 486 manual Int_With_Err 10 Int_With_Err 11 Int_With_Err 12 Int_With_Err 13 Int_With_Err 14 Int_No_Err 15 ; FIXME: not described in 486 manual Int_No_Err 16 Int_With_Err 17 ; The remaining interrupts (18 - 255) do not have error codes. ; We can generate them all in one go with nasm's %rep construct. %assign intNum 18 %rep (256 - 18) Int_No_Err intNum %assign intNum intNum+1 %endrep align 16 g_entryPointTableEnd: [SECTION .data] ; Exported symbols defining the size of handler entry points ; (both with and without error codes). align 4 g_handlerSizeNoErr: dd (After_No_Err - Before_No_Err) align 4 g_handlerSizeErr: dd (After_Err - Before_Err)
frame 1, 05 frame 2, 10 frame 3, 10 endanim
; A026915: a(n) = T(n,0) + T(n,1) + ... + T(n,n), T given by A026907. ; 1,26,100,272,640,1400,2944,6056,12304,24824,49888,100040,200368,401048,802432,1605224,3210832,6422072,12844576,25689608,51379696,102759896,205520320,411041192,822082960,1644166520,3288333664,6576667976,13153336624,26306673944,52613348608,105226697960,210453396688,420906794168,841813589152,1683627179144,3367254359152,6734508719192,13469017439296,26938034879528,53876069760016,107752139521016,215504279043040,431008558087112,862017116175280,1724034232351640,3448068464704384,6896136929409896,13792273858820944,27584547717643064,55169095435287328,110338190870575880,220676381741153008,441352763482307288,882705526964615872,1765411053929233064,3530822107858467472,7061644215716936312,14123288431433874016,28246576862867749448,56493153725735500336,112986307451471002136,225972614902942005760,451945229805884013032,903890459611768027600,1807780919223536056760,3615561838447072115104,7231123676894144231816,14462247353788288465264,28924494707576576932184,57848989415153153866048,115697978830306307733800,231395957660612615469328,462791915321225230940408,925583830642450461882592,1851167661284900923766984,3702335322569801847535792,7404670645139603695073432,14809341290279207390148736,29618682580558414780299368,59237365161116829560600656,118474730322233659121203256,236949460644467318242408480,473898921288934636484818952,947797842577869272969639920,1895595685155738545939281880,3791191370311477091878565824,7582382740622954183757133736,15164765481245908367514269584,30329530962491816735028541304,60659061924983633470057084768,121318123849967266940114171720,242636247699934533880228345648,485272495399869067760456693528,970544990799738135520913389312,1941089981599476271041826780904,3882179963198952542083653564112,7764359926397905084167307130552,15528719852795810168334614263456,31057439705591620336669228529288 lpb $0 sub $0,1 add $2,6 add $1,$2 add $1,$2 mul $1,2 add $1,1 lpe add $1,1 mov $0,$1
#include <CGAL/Polygon_mesh_processing/measure.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> #include <CGAL/Polyhedron_3.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Polygon_mesh_processing/bbox.h> #include <CGAL/Bbox_3.h> #include <iostream> #include <fstream> #include <iterator> #include <list> namespace PMP = CGAL::Polygon_mesh_processing; typedef CGAL::Exact_predicates_inexact_constructions_kernel Epic; typedef CGAL::Exact_predicates_exact_constructions_kernel Epec; template<typename Mesh, typename K> void test_pmesh(const Mesh& pmesh) { typedef typename K::FT FT; typedef typename boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor; typedef typename boost::graph_traits<Mesh>::face_descriptor face_descriptor; typedef typename boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor; typedef typename boost::graph_traits<Mesh>::edge_descriptor edge_descriptor; bool has_border = false; halfedge_descriptor border_he; for(halfedge_descriptor h : halfedges(pmesh)) { if (is_border(h, pmesh)) { border_he = h; has_border = true; break; } } FT border_l = PMP::face_border_length(border_he, pmesh); std::cout << "length of hole border = " << border_l << std::endl; if (has_border) assert(border_l > 0); face_descriptor valid_patch_face; unsigned int count = 0; for(halfedge_descriptor h : halfedges(pmesh)) { if (is_border(h, pmesh) || is_border(opposite(h, pmesh), pmesh)) continue; else { FT edge_length = PMP::edge_length(h, pmesh); FT squared_edge_length = PMP::squared_edge_length(h, pmesh); std::cout << "squared edge length = " << squared_edge_length << std::endl; std::cout << "edge length = " << edge_length << std::endl; FT squared_face_area = PMP::squared_face_area(face(h, pmesh), pmesh); std::cout << "squared face area = " << squared_face_area << std::endl; FT face_area = PMP::face_area(face(h, pmesh), pmesh); std::cout << "face area = " << face_area << std::endl; assert(face_area > 0); if(++count == 20) { valid_patch_face = face(h, pmesh); break; } } } std::list<face_descriptor> patch; patch.push_back(valid_patch_face); while (patch.size() < 5) { face_descriptor f = patch.front(); patch.pop_front(); for(halfedge_descriptor h : halfedges_around_face(halfedge(f, pmesh), pmesh)) { if (boost::graph_traits<Mesh>::null_halfedge() != opposite(h, pmesh)) patch.push_back(face(opposite(h, pmesh), pmesh)); patch.push_back(f); } if (patch.front() == valid_patch_face) break;//back to starting point } FT patch_area = PMP::area(patch, pmesh); std::cout << "patch area = " << patch_area << std::endl; assert(patch_area > 0); FT mesh_area = PMP::area(pmesh); std::cout << "mesh area = " << mesh_area << std::endl; assert(mesh_area >= patch_area); FT mesh_area_np = PMP::area(pmesh, PMP::parameters::geom_traits(K())); std::cout << "mesh area (NP) = " << mesh_area_np << std::endl; assert(mesh_area_np > 0); std::pair<halfedge_descriptor, FT> res = PMP::longest_border(pmesh); if(res.first == boost::graph_traits<Mesh>::null_halfedge()){ std::cout << "mesh has no border" << std::endl; } else { std::cout << "longest border has length = " << res.second <<std::endl; } CGAL::Bbox_3 bb = PMP::bbox(pmesh); std::cout << "bbox x[" << bb.xmin() << "; " << bb.xmax() << "]" << std::endl; std::cout << " y[" << bb.ymin() << "; " << bb.ymax() << "]" << std::endl; std::cout << " z[" << bb.zmin() << "; " << bb.zmax() << "]" << std::endl; CGAL::Bbox_3 bb_v; for(vertex_descriptor vd : vertices(pmesh)) bb_v+=PMP::vertex_bbox(vd, pmesh); CGAL::Bbox_3 bb_f; for(face_descriptor fd : faces(pmesh)) bb_f+=PMP::face_bbox(fd, pmesh); CGAL::Bbox_3 bb_e; for(edge_descriptor ed : edges(pmesh)) bb_e+=PMP::edge_bbox(ed, pmesh); assert(bb==bb_v); assert(bb==bb_f); assert(bb==bb_e); } template <typename Polyhedron, typename K> void test_polyhedron(const char* filename) { std::cout << "Test Polyhedron " << filename << " with Kernel " << typeid(K).name() << std::endl; //run test for a Polyhedron Polyhedron poly; // file should contain oriented polyhedron std::ifstream input(filename); if (!input || !(input >> poly)) { std::cerr << "Error: cannot read Polyhedron : " << filename << "\n"; assert(!poly.empty()); assert(false); return; } test_pmesh<Polyhedron, K>(poly); } template <typename Surface_mesh, typename K> void test_closed_surface_mesh(const char* filename) { std::cout << "Test Surface_mesh " << filename << " with Kernel " << typeid(K).name() << std::endl; Surface_mesh sm; std::ifstream input(filename); if (!input || !(input >> sm)) { std::cerr << "Error: cannot read Surface mesh : " << filename << "\n"; assert(sm.number_of_vertices() > 0); assert(false); return; } test_pmesh<Surface_mesh, K>(sm); typename K::FT vol = PMP::volume(sm); std::cout << "volume = " << vol << std::endl; assert(vol > 0); } template <typename Surface_mesh, typename K> void test_centroid(const char* filename) { std::cout << "Test Surface_mesh " << filename << " with Kernel " << typeid(K).name() << std::endl; Surface_mesh sm; std::ifstream input(filename); input >> sm; typename K::Point_3 p = PMP::centroid(sm); // For data/elephant.off // compare with centroid of 1.000.000 points inside the mesh: // 0.00772887 -0.134923 0.011703 assert (p.x() > 0.007 && p.x() < 0.008); assert (p.y() > -0.14 && p.y() < -0.13); assert (p.z() > 0.01 && p.z() < 0.02); typename K::Vector_3 v(10,20,30); for(typename boost::graph_traits<Surface_mesh>::vertex_descriptor vd : vertices(sm)){ sm.point(vd) = sm.point(vd) + v; } p = PMP::centroid(sm); p = p - v; assert (p.x() > 0.007 && p.x() < 0.008); assert (p.y() > -0.14 && p.y() < -0.13); assert (p.z() > 0.01 && p.z() < 0.02); } template <typename PolygonMesh1, typename PolygonMesh2 > void test_compare() { typedef typename boost::graph_traits<PolygonMesh1>::face_descriptor face_descriptor1; typedef typename boost::graph_traits<PolygonMesh2>::face_descriptor face_descriptor2; namespace PMP = CGAL::Polygon_mesh_processing; PolygonMesh1 mesh1; PolygonMesh2 mesh2; std::vector<std::pair<face_descriptor1, face_descriptor2> > common; common.clear(); std::vector<face_descriptor1> m1_only; std::vector<face_descriptor2> m2_only; /************************* * triangulated and open * * **********************/ std::ifstream input("data/tri1.off"); if(! (input >> mesh1)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); input.open("data/tri2.off"); if(! (input >> mesh2)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); PMP::match_faces(mesh1, mesh2, std::back_inserter(common), std::back_inserter(m1_only), std::back_inserter(m2_only), CGAL::parameters::all_default(), CGAL::parameters::all_default()); assert(common.size() == 7); assert(m1_only.size() == 11); assert(m2_only.size() == 11); /************************* **** quad and closed **** * **********************/ CGAL::clear(mesh1); CGAL::clear(mesh2); common.clear(); m1_only.clear(); m2_only.clear(); input.open("data/cube_quad.off"); if(! (input >> mesh1)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); input.open("data/cube_quad2.off"); if(! (input >> mesh2)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); std::unordered_map<face_descriptor1, std::size_t> fim1; std::unordered_map<face_descriptor2, std::size_t> fim2; std::size_t id = 0; for(const auto& f : faces(mesh1)) { fim1.insert(std::make_pair(f, id++)); } id = 0; for(const auto& f : faces(mesh2)) { fim2.insert(std::make_pair(f, id++)); } PMP::match_faces(mesh1, mesh2, std::back_inserter(common), std::back_inserter(m1_only), std::back_inserter(m2_only), CGAL::parameters::all_default(), CGAL::parameters::all_default()); assert(common.size() == 3); assert(m1_only.size() == 3); assert(fim1[m1_only[0]] == 0); assert(fim1[m1_only[1]] == 3); assert(fim1[m1_only[2]] == 4); assert(m2_only.size() == 3); assert(fim2[m2_only[0]] == 0); assert(fim2[m2_only[1]] == 3); assert(fim2[m2_only[2]] == 4); /************************* **** tri and hole**** * **********************/ CGAL::clear(mesh1); CGAL::clear(mesh2); common.clear(); m1_only.clear(); m2_only.clear(); input.open("data/tri1.off"); if(! (input >> mesh1)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); input.open("data/tri1-hole.off"); if(! (input >> mesh2)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); PMP::match_faces(mesh1, mesh2, std::back_inserter(common), std::back_inserter(m1_only), std::back_inserter(m2_only), CGAL::parameters::all_default(), CGAL::parameters::all_default()); assert(common.size() == 17); assert(m1_only.size() == 1); assert(m2_only.size() == 0); /************************* **** tri and orient**** * **********************/ CGAL::clear(mesh1); CGAL::clear(mesh2); common.clear(); m1_only.clear(); m2_only.clear(); input.open("data/tri2.off"); if(! (input >> mesh1)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); input.open("data/tri2-out.off"); if(! (input >> mesh2)) { std::cerr << "Invalid input." << std::endl; assert (false); return; } input.close(); PMP::match_faces(mesh1, mesh2, std::back_inserter(common), std::back_inserter(m1_only), std::back_inserter(m2_only)); assert(common.size() == 0); assert(m1_only.size() == 18); assert(m2_only.size() == 18); } int main(int argc, char* argv[]) { const char* filename_polyhedron = (argc > 1) ? argv[1] : "data/mech-holes-shark.off"; test_polyhedron<CGAL::Polyhedron_3<Epic>,Epic>(filename_polyhedron); test_polyhedron<CGAL::Polyhedron_3<Epec>,Epec>(filename_polyhedron); const char* filename_surface_mesh = (argc > 1) ? argv[1] : "data/elephant.off"; test_closed_surface_mesh<CGAL::Surface_mesh<Epic::Point_3>,Epic>(filename_surface_mesh); test_closed_surface_mesh<CGAL::Surface_mesh<Epec::Point_3>,Epec>(filename_surface_mesh); // It won't work with Epec for large meshes as it builds up a deep DAG // leading to a stackoverflow when the destructor is called. test_centroid<CGAL::Surface_mesh<Epic::Point_3>,Epic>(filename_surface_mesh); test_compare<CGAL::Polyhedron_3<Epic>, CGAL::Surface_mesh<Epic::Point_3> >(); test_compare<CGAL::Polyhedron_3<Epec>, CGAL::Surface_mesh<Epec::Point_3> >(); test_compare<CGAL::Surface_mesh<Epic::Point_3>, CGAL::Polyhedron_3<Epic> >(); test_compare<CGAL::Surface_mesh<Epec::Point_3>, CGAL::Polyhedron_3<Epec> >(); std::cerr << "All done." << std::endl; return 0; }
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %r8 push %r9 push %rdx push %rsi // Store mov $0xa80, %rdx xor $65173, %r10 movw $0x5152, (%rdx) nop nop nop nop nop sub %r14, %r14 // Store lea addresses_US+0xdbe2, %r8 nop nop cmp $40505, %r11 movw $0x5152, (%r8) // Exception!!! nop nop mov (0), %r8 nop nop nop nop add $13617, %r10 // Load mov $0x3c0, %r10 nop nop nop nop nop sub %rsi, %rsi mov (%r10), %r11 nop inc %rdx // Load lea addresses_UC+0x19fc0, %r11 nop nop nop nop sub $27521, %r8 mov (%r11), %r14 nop dec %rdx // Faulty Load lea addresses_A+0x11bc0, %rdx nop nop nop xor $60459, %r14 mov (%rdx), %r9 lea oracles, %r14 and $0xff, %r9 shlq $12, %r9 mov (%r14,%r9,1), %r9 pop %rsi pop %rdx pop %r9 pop %r8 pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'size': 2, 'AVXalign': False, 'NT': True, 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_P', 'size': 8, 'AVXalign': False, 'NT': True, 'congruent': 10, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 10, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'00': 5930} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for cast expressions, including // 1) C-style casts like '(int) x' // 2) C++ functional casts like 'int(x)' // 3) C++ named casts like 'static_cast<int>(x)' // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/RecordLayout.h" #include "clang/Basic/PartialDiagnostic.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "llvm/ADT/SmallVector.h" #include <set> using namespace clang; enum TryCastResult { TC_NotApplicable, ///< The cast method is not applicable. TC_Success, ///< The cast method is appropriate and successful. TC_Extension, ///< The cast method is appropriate and accepted as a ///< language extension. TC_Failed ///< The cast method is appropriate, but failed. A ///< diagnostic has been emitted. }; static bool isValidCast(TryCastResult TCR) { return TCR == TC_Success || TCR == TC_Extension; } enum CastType { CT_Const, ///< const_cast CT_Static, ///< static_cast CT_Reinterpret, ///< reinterpret_cast CT_Dynamic, ///< dynamic_cast CT_CStyle, ///< (Type)expr CT_Functional, ///< Type(expr) CT_Addrspace ///< addrspace_cast }; namespace { struct CastOperation { CastOperation(Sema &S, QualType destType, ExprResult src) : Self(S), SrcExpr(src), DestType(destType), ResultType(destType.getNonLValueExprType(S.Context)), ValueKind(Expr::getValueKindForType(destType)), Kind(CK_Dependent), IsARCUnbridgedCast(false) { if (const BuiltinType *placeholder = src.get()->getType()->getAsPlaceholderType()) { PlaceholderKind = placeholder->getKind(); } else { PlaceholderKind = (BuiltinType::Kind) 0; } } Sema &Self; ExprResult SrcExpr; QualType DestType; QualType ResultType; ExprValueKind ValueKind; CastKind Kind; BuiltinType::Kind PlaceholderKind; CXXCastPath BasePath; bool IsARCUnbridgedCast; SourceRange OpRange; SourceRange DestRange; // Top-level semantics-checking routines. void CheckConstCast(); void CheckReinterpretCast(); void CheckStaticCast(); void CheckDynamicCast(); void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); void CheckCStyleCast(); void CheckBuiltinBitCast(); void CheckAddrspaceCast(); void updatePartOfExplicitCastFlags(CastExpr *CE) { // Walk down from the CE to the OrigSrcExpr, and mark all immediate // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE) ICE->setIsPartOfExplicitCast(true); } /// Complete an apparently-successful cast operation that yields /// the given expression. ExprResult complete(CastExpr *castExpr) { // If this is an unbridged cast, wrap the result in an implicit // cast that yields the unbridged-cast placeholder type. if (IsARCUnbridgedCast) { castExpr = ImplicitCastExpr::Create(Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent, castExpr, nullptr, castExpr->getValueKind()); } updatePartOfExplicitCastFlags(castExpr); return castExpr; } // Internal convenience methods. /// Try to handle the given placeholder expression kind. Return /// true if the source expression has the appropriate placeholder /// kind. A placeholder can only be claimed once. bool claimPlaceholder(BuiltinType::Kind K) { if (PlaceholderKind != K) return false; PlaceholderKind = (BuiltinType::Kind) 0; return true; } bool isPlaceholder() const { return PlaceholderKind != 0; } bool isPlaceholder(BuiltinType::Kind K) const { return PlaceholderKind == K; } // Language specific cast restrictions for address spaces. void checkAddressSpaceCast(QualType SrcType, QualType DestType); void checkCastAlign() { Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); } void checkObjCConversion(Sema::CheckedConversionKind CCK) { assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()); Expr *src = SrcExpr.get(); if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) == Sema::ACR_unbridged) IsARCUnbridgedCast = true; SrcExpr = src; } void checkQualifiedDestType() { // Destination type may not be qualified with __ptrauth. if (DestType.getPointerAuth()) { Self.Diag(DestRange.getBegin(), diag::err_ptrauth_qualifier_cast) << DestType << DestRange; } } /// Check for and handle non-overload placeholder expressions. void checkNonOverloadPlaceholders() { if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) return; SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); if (SrcExpr.isInvalid()) return; PlaceholderKind = (BuiltinType::Kind) 0; } }; void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType, SourceLocation OpLoc) { if (const auto *PtrType = dyn_cast<PointerType>(FromType)) { if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) { if (const auto *DestType = dyn_cast<PointerType>(ToType)) { if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) { S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer); } } } } } struct CheckNoDerefRAII { CheckNoDerefRAII(CastOperation &Op) : Op(Op) {} ~CheckNoDerefRAII() { if (!Op.SrcExpr.isInvalid()) CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType, Op.OpRange.getBegin()); } CastOperation &Op; }; } static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, QualType DestType); // The Try functions attempt a specific way of casting. If they succeed, they // return TC_Success. If their way of casting is not appropriate for the given // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic // to emit if no other way succeeds. If their way of casting is appropriate but // fails, they return TC_Failed and *must* set diag; they can set it to 0 if // they emit a specialized diagnostic. // All diagnostics returned by these functions must expect the same three // arguments: // %0: Cast Type (a value from the CastType enumeration) // %1: Source Type // %2: Destination Type static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, bool CStyle, CastKind &Kind, CXXCastPath &BasePath, unsigned &msg); static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath); static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath); static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, bool CStyle, SourceRange OpRange, QualType OrigSrcType, QualType OrigDestType, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath); static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, QualType DestType,bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath); static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization); static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath, bool ListInitialization); static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, unsigned &msg); static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind); static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, unsigned &msg, CastKind &Kind); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc) { assert(!D.isInvalidType()); TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); if (D.isInvalidType()) return ExprError(); if (getLangOpts().CPlusPlus) { // Check that there are no default arguments (C++ only). CheckExtraCXXDefaultArguments(D); } return BuildCXXNamedCast(OpLoc, Kind, TInfo, E, SourceRange(LAngleBracketLoc, RAngleBracketLoc), SourceRange(LParenLoc, RParenLoc)); } ExprResult Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *DestTInfo, Expr *E, SourceRange AngleBrackets, SourceRange Parens) { ExprResult Ex = E; QualType DestType = DestTInfo->getType(); // If the type is dependent, we won't do the semantic analysis now. bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent(); CastOperation Op(*this, DestType, E); Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); Op.DestRange = AngleBrackets; Op.checkQualifiedDestType(); switch (Kind) { default: llvm_unreachable("Unknown C++ cast!"); case tok::kw_addrspace_cast: if (!TypeDependent) { Op.CheckAddrspaceCast(); if (Op.SrcExpr.isInvalid()) return ExprError(); } return Op.complete(CXXAddrspaceCastExpr::Create( Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); case tok::kw_const_cast: if (!TypeDependent) { Op.CheckConstCast(); if (Op.SrcExpr.isInvalid()) return ExprError(); DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); } return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.SrcExpr.get(), DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); case tok::kw_dynamic_cast: { // dynamic_cast is not supported in C++ for OpenCL. if (getLangOpts().OpenCLCPlusPlus) { return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) << "dynamic_cast"); } if (!TypeDependent) { Op.CheckDynamicCast(); if (Op.SrcExpr.isInvalid()) return ExprError(); } return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), &Op.BasePath, DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); } case tok::kw_reinterpret_cast: { if (!TypeDependent) { Op.CheckReinterpretCast(); if (Op.SrcExpr.isInvalid()) return ExprError(); DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); } return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), nullptr, DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); } case tok::kw_static_cast: { if (!TypeDependent) { Op.CheckStaticCast(); if (Op.SrcExpr.isInvalid()) return ExprError(); DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); } return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), &Op.BasePath, DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); } } } ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D, ExprResult Operand, SourceLocation RParenLoc) { assert(!D.isInvalidType()); TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType()); if (D.isInvalidType()) return ExprError(); return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc); } ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc) { CastOperation Op(*this, TSI->getType(), Operand); Op.OpRange = SourceRange(KWLoc, RParenLoc); TypeLoc TL = TSI->getTypeLoc(); Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) { Op.CheckBuiltinBitCast(); if (Op.SrcExpr.isInvalid()) return ExprError(); } BuiltinBitCastExpr *BCE = new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), TSI, KWLoc, RParenLoc); return Op.complete(BCE); } /// Try to diagnose a failed overloaded cast. Returns true if /// diagnostics were emitted. static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, SourceRange range, Expr *src, QualType destType, bool listInitialization) { switch (CT) { // These cast kinds don't consider user-defined conversions. case CT_Const: case CT_Reinterpret: case CT_Dynamic: case CT_Addrspace: return false; // These do. case CT_Static: case CT_CStyle: case CT_Functional: break; } QualType srcType = src->getType(); if (!destType->isRecordType() && !srcType->isRecordType()) return false; InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); InitializationKind initKind = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), range, listInitialization) : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, listInitialization) : InitializationKind::CreateCast(/*type range?*/ range); InitializationSequence sequence(S, entity, initKind, src); assert(sequence.Failed() && "initialization succeeded on second try?"); switch (sequence.getFailureKind()) { default: return false; case InitializationSequence::FK_ConstructorOverloadFailed: case InitializationSequence::FK_UserConversionOverloadFailed: break; } OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); unsigned msg = 0; OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; switch (sequence.getFailedOverloadResult()) { case OR_Success: llvm_unreachable("successful failed overload"); case OR_No_Viable_Function: if (candidates.empty()) msg = diag::err_ovl_no_conversion_in_cast; else msg = diag::err_ovl_no_viable_conversion_in_cast; howManyCandidates = OCD_AllCandidates; break; case OR_Ambiguous: msg = diag::err_ovl_ambiguous_conversion_in_cast; howManyCandidates = OCD_AmbiguousCandidates; break; case OR_Deleted: msg = diag::err_ovl_deleted_conversion_in_cast; howManyCandidates = OCD_ViableCandidates; break; } candidates.NoteCandidates( PartialDiagnosticAt(range.getBegin(), S.PDiag(msg) << CT << srcType << destType << range << src->getSourceRange()), S, howManyCandidates, src); return true; } /// Diagnose a failed cast. static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, SourceRange opRange, Expr *src, QualType destType, bool listInitialization) { if (msg == diag::err_bad_cxx_cast_generic && tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, listInitialization)) return; S.Diag(opRange.getBegin(), msg) << castType << src->getType() << destType << opRange << src->getSourceRange(); // Detect if both types are (ptr to) class, and note any incompleteness. int DifferentPtrness = 0; QualType From = destType; if (auto Ptr = From->getAs<PointerType>()) { From = Ptr->getPointeeType(); DifferentPtrness++; } QualType To = src->getType(); if (auto Ptr = To->getAs<PointerType>()) { To = Ptr->getPointeeType(); DifferentPtrness--; } if (!DifferentPtrness) { auto RecFrom = From->getAs<RecordType>(); auto RecTo = To->getAs<RecordType>(); if (RecFrom && RecTo) { auto DeclFrom = RecFrom->getAsCXXRecordDecl(); if (!DeclFrom->isCompleteDefinition()) S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom; auto DeclTo = RecTo->getAsCXXRecordDecl(); if (!DeclTo->isCompleteDefinition()) S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo; } } } namespace { /// The kind of unwrapping we did when determining whether a conversion casts /// away constness. enum CastAwayConstnessKind { /// The conversion does not cast away constness. CACK_None = 0, /// We unwrapped similar types. CACK_Similar = 1, /// We unwrapped dissimilar types with similar representations (eg, a pointer /// versus an Objective-C object pointer). CACK_SimilarKind = 2, /// We unwrapped representationally-unrelated types, such as a pointer versus /// a pointer-to-member. CACK_Incoherent = 3, }; } /// Unwrap one level of types for CastsAwayConstness. /// /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from /// both types, provided that they're both pointer-like or array-like. Unlike /// the Sema function, doesn't care if the unwrapped pieces are related. /// /// This function may remove additional levels as necessary for correctness: /// the resulting T1 is unwrapped sufficiently that it is never an array type, /// so that its qualifiers can be directly compared to those of T2 (which will /// have the combined set of qualifiers from all indermediate levels of T2), /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers /// with those from T2. static CastAwayConstnessKind unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) { enum { None, Ptr, MemPtr, BlockPtr, Array }; auto Classify = [](QualType T) { if (T->isAnyPointerType()) return Ptr; if (T->isMemberPointerType()) return MemPtr; if (T->isBlockPointerType()) return BlockPtr; // We somewhat-arbitrarily don't look through VLA types here. This is at // least consistent with the behavior of UnwrapSimilarTypes. if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array; return None; }; auto Unwrap = [&](QualType T) { if (auto *AT = Context.getAsArrayType(T)) return AT->getElementType(); return T->getPointeeType(); }; CastAwayConstnessKind Kind; if (T2->isReferenceType()) { // Special case: if the destination type is a reference type, unwrap it as // the first level. (The source will have been an lvalue expression in this // case, so there is no corresponding "reference to" in T1 to remove.) This // simulates removing a "pointer to" from both sides. T2 = T2->getPointeeType(); Kind = CastAwayConstnessKind::CACK_Similar; } else if (Context.UnwrapSimilarTypes(T1, T2)) { Kind = CastAwayConstnessKind::CACK_Similar; } else { // Try unwrapping mismatching levels. int T1Class = Classify(T1); if (T1Class == None) return CastAwayConstnessKind::CACK_None; int T2Class = Classify(T2); if (T2Class == None) return CastAwayConstnessKind::CACK_None; T1 = Unwrap(T1); T2 = Unwrap(T2); Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind : CastAwayConstnessKind::CACK_Incoherent; } // We've unwrapped at least one level. If the resulting T1 is a (possibly // multidimensional) array type, any qualifier on any matching layer of // T2 is considered to correspond to T1. Decompose down to the element // type of T1 so that we can compare properly. while (true) { Context.UnwrapSimilarArrayTypes(T1, T2); if (Classify(T1) != Array) break; auto T2Class = Classify(T2); if (T2Class == None) break; if (T2Class != Array) Kind = CastAwayConstnessKind::CACK_Incoherent; else if (Kind != CastAwayConstnessKind::CACK_Incoherent) Kind = CastAwayConstnessKind::CACK_SimilarKind; T1 = Unwrap(T1); T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers()); } return Kind; } /// Check if the pointer conversion from SrcType to DestType casts away /// constness as defined in C++ [expr.const.cast]. This is used by the cast /// checkers. Both arguments must denote pointer (possibly to member) types. /// /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. static CastAwayConstnessKind CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, bool CheckCVR, bool CheckObjCLifetime, QualType *TheOffendingSrcType = nullptr, QualType *TheOffendingDestType = nullptr, Qualifiers *CastAwayQualifiers = nullptr) { // If the only checking we care about is for Objective-C lifetime qualifiers, // and we're not in ObjC mode, there's nothing to check. if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC) return CastAwayConstnessKind::CACK_None; if (!DestType->isReferenceType()) { assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member."); assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member."); } QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), UnwrappedDestType = Self.Context.getCanonicalType(DestType); // Find the qualifiers. We only care about cvr-qualifiers for the // purpose of this check, because other qualifiers (address spaces, // Objective-C GC, etc.) are part of the type's identity. QualType PrevUnwrappedSrcType = UnwrappedSrcType; QualType PrevUnwrappedDestType = UnwrappedDestType; auto WorstKind = CastAwayConstnessKind::CACK_Similar; bool AllConstSoFar = true; while (auto Kind = unwrapCastAwayConstnessLevel( Self.Context, UnwrappedSrcType, UnwrappedDestType)) { // Track the worst kind of unwrap we needed to do before we found a // problem. if (Kind > WorstKind) WorstKind = Kind; // Determine the relevant qualifiers at this level. Qualifiers SrcQuals, DestQuals; Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); // We do not meaningfully track object const-ness of Objective-C object // types. Remove const from the source type if either the source or // the destination is an Objective-C object type. if (UnwrappedSrcType->isObjCObjectType() || UnwrappedDestType->isObjCObjectType()) SrcQuals.removeConst(); if (CheckCVR) { Qualifiers SrcCvrQuals = Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()); Qualifiers DestCvrQuals = Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()); if (SrcCvrQuals != DestCvrQuals) { if (CastAwayQualifiers) *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals; // If we removed a cvr-qualifier, this is casting away 'constness'. if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) { if (TheOffendingSrcType) *TheOffendingSrcType = PrevUnwrappedSrcType; if (TheOffendingDestType) *TheOffendingDestType = PrevUnwrappedDestType; return WorstKind; } // If any prior level was not 'const', this is also casting away // 'constness'. We noted the outermost type missing a 'const' already. if (!AllConstSoFar) return WorstKind; } } if (CheckObjCLifetime && !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) return WorstKind; // If we found our first non-const-qualified type, this may be the place // where things start to go wrong. if (AllConstSoFar && !DestQuals.hasConst()) { AllConstSoFar = false; if (TheOffendingSrcType) *TheOffendingSrcType = PrevUnwrappedSrcType; if (TheOffendingDestType) *TheOffendingDestType = PrevUnwrappedDestType; } PrevUnwrappedSrcType = UnwrappedSrcType; PrevUnwrappedDestType = UnwrappedDestType; } return CastAwayConstnessKind::CACK_None; } static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK, unsigned &DiagID) { switch (CACK) { case CastAwayConstnessKind::CACK_None: llvm_unreachable("did not cast away constness"); case CastAwayConstnessKind::CACK_Similar: // FIXME: Accept these as an extension too? case CastAwayConstnessKind::CACK_SimilarKind: DiagID = diag::err_bad_cxx_cast_qualifiers_away; return TC_Failed; case CastAwayConstnessKind::CACK_Incoherent: DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent; return TC_Extension; } llvm_unreachable("unexpected cast away constness kind"); } /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- /// checked downcasts in class hierarchies. void CastOperation::CheckDynamicCast() { CheckNoDerefRAII NoderefCheck(*this); if (ValueKind == VK_RValue) SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); else if (isPlaceholder()) SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; QualType OrigSrcType = SrcExpr.get()->getType(); QualType DestType = Self.Context.getCanonicalType(this->DestType); // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, // or "pointer to cv void". QualType DestPointee; const PointerType *DestPointer = DestType->getAs<PointerType>(); const ReferenceType *DestReference = nullptr; if (DestPointer) { DestPointee = DestPointer->getPointeeType(); } else if ((DestReference = DestType->getAs<ReferenceType>())) { DestPointee = DestReference->getPointeeType(); } else { Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) << this->DestType << DestRange; SrcExpr = ExprError(); return; } const RecordType *DestRecord = DestPointee->getAs<RecordType>(); if (DestPointee->isVoidType()) { assert(DestPointer && "Reference to void is not possible"); } else if (DestRecord) { if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, diag::err_bad_cast_incomplete, DestRange)) { SrcExpr = ExprError(); return; } } else { Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) << DestPointee.getUnqualifiedType() << DestRange; SrcExpr = ExprError(); return; } // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to // complete class type, [...]. If T is an lvalue reference type, v shall be // an lvalue of a complete class type, [...]. If T is an rvalue reference // type, v shall be an expression having a complete class type, [...] QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); QualType SrcPointee; if (DestPointer) { if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { SrcPointee = SrcPointer->getPointeeType(); } else { Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } else if (DestReference->isLValueReferenceType()) { if (!SrcExpr.get()->isLValue()) { Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) << CT_Dynamic << OrigSrcType << this->DestType << OpRange; } SrcPointee = SrcType; } else { // If we're dynamic_casting from a prvalue to an rvalue reference, we need // to materialize the prvalue before we bind the reference to it. if (SrcExpr.get()->isRValue()) SrcExpr = Self.CreateMaterializeTemporaryExpr( SrcType, SrcExpr.get(), /*IsLValueReference*/ false); SrcPointee = SrcType; } const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); if (SrcRecord) { if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, diag::err_bad_cast_incomplete, SrcExpr.get())) { SrcExpr = ExprError(); return; } } else { Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } assert((DestPointer || DestReference) && "Bad destination non-ptr/ref slipped through."); assert((DestRecord || DestPointee->isVoidType()) && "Bad destination pointee slipped through."); assert(SrcRecord && "Bad source pointee slipped through."); // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) << CT_Dynamic << OrigSrcType << this->DestType << OpRange; SrcExpr = ExprError(); return; } // C++ 5.2.7p3: If the type of v is the same as the required result type, // [except for cv]. if (DestRecord == SrcRecord) { Kind = CK_NoOp; return; } // C++ 5.2.7p5 // Upcasts are resolved statically. if (DestRecord && Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, OpRange.getBegin(), OpRange, &BasePath)) { SrcExpr = ExprError(); return; } Kind = CK_DerivedToBase; return; } // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); assert(SrcDecl && "Definition missing"); if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); } // dynamic_cast is not available with -fno-rtti. // As an exception, dynamic_cast to void* is available because it doesn't // use RTTI. if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); SrcExpr = ExprError(); return; } // Done. Everything else is run-time checks. Kind = CK_Dynamic; } /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. /// Refer to C++ 5.2.11 for details. const_cast is typically used in code /// like this: /// const char *str = "literal"; /// legacy_function(const_cast\<char*\>(str)); void CastOperation::CheckConstCast() { CheckNoDerefRAII NoderefCheck(*this); if (ValueKind == VK_RValue) SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); else if (isPlaceholder()) SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; unsigned msg = diag::err_bad_cxx_cast_generic; auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg); if (TCR != TC_Success && msg != 0) { Self.Diag(OpRange.getBegin(), msg) << CT_Const << SrcExpr.get()->getType() << DestType << OpRange; } if (!isValidCast(TCR)) SrcExpr = ExprError(); } void CastOperation::CheckAddrspaceCast() { unsigned msg = diag::err_bad_cxx_cast_generic; auto TCR = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind); if (TCR != TC_Success && msg != 0) { Self.Diag(OpRange.getBegin(), msg) << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange; } if (!isValidCast(TCR)) SrcExpr = ExprError(); } /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast /// or downcast between respective pointers or references. static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, QualType DestType, SourceRange OpRange) { QualType SrcType = SrcExpr->getType(); // When casting from pointer or reference, get pointee type; use original // type otherwise. const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); const CXXRecordDecl *SrcRD = SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); // Examining subobjects for records is only possible if the complete and // valid definition is available. Also, template instantiation is not // allowed here. if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) return; const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) return; enum { ReinterpretUpcast, ReinterpretDowncast } ReinterpretKind; CXXBasePaths BasePaths; if (SrcRD->isDerivedFrom(DestRD, BasePaths)) ReinterpretKind = ReinterpretUpcast; else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) ReinterpretKind = ReinterpretDowncast; else return; bool VirtualBase = true; bool NonZeroOffset = false; for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), E = BasePaths.end(); I != E; ++I) { const CXXBasePath &Path = *I; CharUnits Offset = CharUnits::Zero(); bool IsVirtual = false; for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); IElem != EElem; ++IElem) { IsVirtual = IElem->Base->isVirtual(); if (IsVirtual) break; const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); assert(BaseRD && "Base type should be a valid unqualified class type"); // Don't check if any base has invalid declaration or has no definition // since it has no layout info. const CXXRecordDecl *Class = IElem->Class, *ClassDefinition = Class->getDefinition(); if (Class->isInvalidDecl() || !ClassDefinition || !ClassDefinition->isCompleteDefinition()) return; const ASTRecordLayout &DerivedLayout = Self.Context.getASTRecordLayout(Class); Offset += DerivedLayout.getBaseClassOffset(BaseRD); } if (!IsVirtual) { // Don't warn if any path is a non-virtually derived base at offset zero. if (Offset.isZero()) return; // Offset makes sense only for non-virtual bases. else NonZeroOffset = true; } VirtualBase = VirtualBase && IsVirtual; } (void) NonZeroOffset; // Silence set but not used warning. assert((VirtualBase || NonZeroOffset) && "Should have returned if has non-virtual base with zero offset"); QualType BaseType = ReinterpretKind == ReinterpretUpcast? DestType : SrcType; QualType DerivedType = ReinterpretKind == ReinterpretUpcast? SrcType : DestType; SourceLocation BeginLoc = OpRange.getBegin(); Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) << OpRange; Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) << int(ReinterpretKind) << FixItHint::CreateReplacement(BeginLoc, "static_cast"); } /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is /// valid. /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code /// like this: /// char *bytes = reinterpret_cast\<char*\>(int_ptr); void CastOperation::CheckReinterpretCast() { if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); else checkNonOverloadPlaceholders(); if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; unsigned msg = diag::err_bad_cxx_cast_generic; TryCastResult tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg, Kind); if (tcr != TC_Success && msg != 0) { if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { //FIXME: &f<int>; is overloaded and resolvable Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) << OverloadExpr::find(SrcExpr.get()).Expression->getName() << DestType << OpRange; Self.NoteAllOverloadCandidates(SrcExpr.get()); } else { diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType, /*listInitialization=*/false); } } if (isValidCast(tcr)) { if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) checkObjCConversion(Sema::CCK_OtherCast); DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); } else { SrcExpr = ExprError(); } } /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making /// implicit conversions explicit and getting rid of data loss warnings. void CastOperation::CheckStaticCast() { CheckNoDerefRAII NoderefCheck(*this); if (isPlaceholder()) { checkNonOverloadPlaceholders(); if (SrcExpr.isInvalid()) return; } // This test is outside everything else because it's the only case where // a non-lvalue-reference target type does not lead to decay. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". if (DestType->isVoidType()) { Kind = CK_ToVoid; if (claimPlaceholder(BuiltinType::Overload)) { Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, false, // Decay Function to ptr true, // Complain OpRange, DestType, diag::err_bad_static_cast_overload); if (SrcExpr.isInvalid()) return; } SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); return; } if (ValueKind == VK_RValue && !DestType->isRecordType() && !isPlaceholder(BuiltinType::Overload)) { SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; } unsigned msg = diag::err_bad_cxx_cast_generic; TryCastResult tcr = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, Kind, BasePath, /*ListInitialization=*/false); if (tcr != TC_Success && msg != 0) { if (SrcExpr.isInvalid()) return; if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) << oe->getName() << DestType << OpRange << oe->getQualifierLoc().getSourceRange(); Self.NoteAllOverloadCandidates(SrcExpr.get()); } else { diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, /*listInitialization=*/false); } } if (isValidCast(tcr)) { if (Kind == CK_BitCast) checkCastAlign(); if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) checkObjCConversion(Sema::CCK_OtherCast); } else { SrcExpr = ExprError(); } } static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) { auto *SrcPtrType = SrcType->getAs<PointerType>(); if (!SrcPtrType) return false; auto *DestPtrType = DestType->getAs<PointerType>(); if (!DestPtrType) return false; return SrcPtrType->getPointeeType().getAddressSpace() != DestPtrType->getPointeeType().getAddressSpace(); } /// TryStaticCast - Check if a static cast can be performed, and do so if /// possible. If @p CStyle, ignore access restrictions on hierarchy casting /// and casting away constness. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath, bool ListInitialization) { // Determine whether we have the semantics of a C-style cast. bool CStyle = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); // The order the tests is not entirely arbitrary. There is one conversion // that can be handled in two different ways. Given: // struct A {}; // struct B : public A { // B(); B(const A&); // }; // const A &a = B(); // the cast static_cast<const B&>(a) could be seen as either a static // reference downcast, or an explicit invocation of the user-defined // conversion using B's conversion constructor. // DR 427 specifies that the downcast is to be applied here. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". // Done outside this function. TryCastResult tcr; // C++ 5.2.9p5, reference downcast. // See the function for details. // DR 427 specifies that this is to be applied before paragraph 2. tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange, msg, Kind, BasePath); if (tcr != TC_NotApplicable) return tcr; // C++11 [expr.static.cast]p3: // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath, msg); if (tcr != TC_NotApplicable) return tcr; // C++ 5.2.9p2: An expression e can be explicitly converted to a type T // [...] if the declaration "T t(e);" is well-formed, [...]. tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind, ListInitialization); if (SrcExpr.isInvalid()) return TC_Failed; if (tcr != TC_NotApplicable) return tcr; // C++ 5.2.9p6: May apply the reverse of any standard conversion, except // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean // conversions, subject to further restrictions. // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal // of qualification conversions impossible. // In the CStyle case, the earlier attempt to const_cast should have taken // care of reverse qualification conversions. QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly // converted to an integral type. [...] A value of a scoped enumeration type // can also be explicitly converted to a floating-point type [...]. if (const EnumType *Enum = SrcType->getAs<EnumType>()) { if (Enum->getDecl()->isScoped()) { if (DestType->isBooleanType()) { Kind = CK_IntegralToBoolean; return TC_Success; } else if (DestType->isIntegralType(Self.Context)) { Kind = CK_IntegralCast; return TC_Success; } else if (DestType->isRealFloatingType()) { Kind = CK_IntegralToFloating; return TC_Success; } } } // Reverse integral promotion/conversion. All such conversions are themselves // again integral promotions or conversions and are thus already handled by // p2 (TryDirectInitialization above). // (Note: any data loss warnings should be suppressed.) // The exception is the reverse of enum->integer, i.e. integer->enum (and // enum->enum). See also C++ 5.2.9p7. // The same goes for reverse floating point promotion/conversion and // floating-integral conversions. Again, only floating->enum is relevant. if (DestType->isEnumeralType()) { if (Self.RequireCompleteType(OpRange.getBegin(), DestType, diag::err_bad_cast_incomplete)) { SrcExpr = ExprError(); return TC_Failed; } if (SrcType->isIntegralOrEnumerationType()) { // [expr.static.cast]p10 If the enumeration type has a fixed underlying // type, the value is first converted to that type by integral conversion const EnumType *Enum = DestType->getAs<EnumType>(); Kind = Enum->getDecl()->isFixed() && Enum->getDecl()->getIntegerType()->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast; return TC_Success; } else if (SrcType->isRealFloatingType()) { Kind = CK_FloatingToIntegral; return TC_Success; } } // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, Kind, BasePath); if (tcr != TC_NotApplicable) return tcr; // Reverse member pointer conversion. C++ 4.11 specifies member pointer // conversion. C++ 5.2.9p9 has additional information. // DR54's access restrictions apply here also. tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, OpRange, msg, Kind, BasePath); if (tcr != TC_NotApplicable) return tcr; // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to // void*. C++ 5.2.9p10 specifies additional restrictions, which really is // just the usual constness stuff. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { QualType SrcPointee = SrcPointer->getPointeeType(); if (SrcPointee->isVoidType()) { if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { QualType DestPointee = DestPointer->getPointeeType(); if (DestPointee->isIncompleteOrObjectType()) { // This is definitely the intended conversion, but it might fail due // to a qualifier violation. Note that we permit Objective-C lifetime // and GC qualifier mismatches here. if (!CStyle) { Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); DestPointeeQuals.removeObjCGCAttr(); DestPointeeQuals.removeObjCLifetime(); SrcPointeeQuals.removeObjCGCAttr(); SrcPointeeQuals.removeObjCLifetime(); if (DestPointeeQuals != SrcPointeeQuals && !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { msg = diag::err_bad_cxx_cast_qualifiers_away; return TC_Failed; } } Kind = IsAddressSpaceConversion(SrcType, DestType) ? CK_AddressSpaceConversion : CK_BitCast; return TC_Success; } // Microsoft permits static_cast from 'pointer-to-void' to // 'pointer-to-function'. if (!CStyle && Self.getLangOpts().MSVCCompat && DestPointee->isFunctionType()) { Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; Kind = CK_BitCast; return TC_Success; } } else if (DestType->isObjCObjectPointerType()) { // allow both c-style cast and static_cast of objective-c pointers as // they are pervasive. Kind = CK_CPointerToObjCPointerCast; return TC_Success; } else if (CStyle && DestType->isBlockPointerType()) { // allow c-style cast of void * to block pointers. Kind = CK_AnyPointerToBlockPointerCast; return TC_Success; } } } // Allow arbitrary objective-c pointer conversion with static casts. if (SrcType->isObjCObjectPointerType() && DestType->isObjCObjectPointerType()) { Kind = CK_BitCast; return TC_Success; } // Allow ns-pointer to cf-pointer conversion in either direction // with static casts. if (!CStyle && Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) return TC_Success; // See if it looks like the user is trying to convert between // related record types, and select a better diagnostic if so. if (auto SrcPointer = SrcType->getAs<PointerType>()) if (auto DestPointer = DestType->getAs<PointerType>()) if (SrcPointer->getPointeeType()->getAs<RecordType>() && DestPointer->getPointeeType()->getAs<RecordType>()) msg = diag::err_bad_cxx_cast_unrelated_class; // We tried everything. Everything! Nothing works! :-( return TC_NotApplicable; } /// Tests whether a conversion according to N2844 is valid. TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, bool CStyle, CastKind &Kind, CXXCastPath &BasePath, unsigned &msg) { // C++11 [expr.static.cast]p3: // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); if (!R) return TC_NotApplicable; if (!SrcExpr->isGLValue()) return TC_NotApplicable; // Because we try the reference downcast before this function, from now on // this is the only cast possibility, so we issue an error if we fail now. // FIXME: Should allow casting away constness if CStyle. QualType FromType = SrcExpr->getType(); QualType ToType = R->getPointeeType(); if (CStyle) { FromType = FromType.getUnqualifiedType(); ToType = ToType.getUnqualifiedType(); } Sema::ReferenceConversions RefConv; Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship( SrcExpr->getBeginLoc(), ToType, FromType, &RefConv); if (RefResult != Sema::Ref_Compatible) { if (CStyle || RefResult == Sema::Ref_Incompatible) return TC_NotApplicable; // Diagnose types which are reference-related but not compatible here since // we can provide better diagnostics. In these cases forwarding to // [expr.static.cast]p4 should never result in a well-formed cast. msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast : diag::err_bad_rvalue_to_rvalue_cast; return TC_Failed; } if (RefConv & Sema::ReferenceConversions::DerivedToBase) { Kind = CK_DerivedToBase; CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/true); if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(), R->getPointeeType(), Paths)) return TC_NotApplicable; Self.BuildBasePathArray(Paths, BasePath); } else Kind = CK_NoOp; return TC_Success; } /// Tests whether a conversion according to C++ 5.2.9p5 is valid. TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be // cast to type "reference to cv2 D", where D is a class derived from B, // if a valid standard conversion from "pointer to D" to "pointer to B" // exists, cv2 >= cv1, and B is not a virtual base class of D. // In addition, DR54 clarifies that the base must be accessible in the // current context. Although the wording of DR54 only applies to the pointer // variant of this rule, the intent is clearly for it to apply to the this // conversion as well. const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); if (!DestReference) { return TC_NotApplicable; } bool RValueRef = DestReference->isRValueReferenceType(); if (!RValueRef && !SrcExpr->isLValue()) { // We know the left side is an lvalue reference, so we can suggest a reason. msg = diag::err_bad_cxx_cast_rvalue; return TC_NotApplicable; } QualType DestPointee = DestReference->getPointeeType(); // FIXME: If the source is a prvalue, we should issue a warning (because the // cast always has undefined behavior), and for AST consistency, we should // materialize a temporary. return TryStaticDowncast(Self, Self.Context.getCanonicalType(SrcExpr->getType()), Self.Context.getCanonicalType(DestPointee), CStyle, OpRange, SrcExpr->getType(), DestType, msg, Kind, BasePath); } /// Tests whether a conversion according to C++ 5.2.9p8 is valid. TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class // type, can be converted to an rvalue of type "pointer to cv2 D", where D // is a class derived from B, if a valid standard conversion from "pointer // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base // class of D. // In addition, DR54 clarifies that the base must be accessible in the // current context. const PointerType *DestPointer = DestType->getAs<PointerType>(); if (!DestPointer) { return TC_NotApplicable; } const PointerType *SrcPointer = SrcType->getAs<PointerType>(); if (!SrcPointer) { msg = diag::err_bad_static_cast_pointer_nonpointer; return TC_NotApplicable; } return TryStaticDowncast(Self, Self.Context.getCanonicalType(SrcPointer->getPointeeType()), Self.Context.getCanonicalType(DestPointer->getPointeeType()), CStyle, OpRange, SrcType, DestType, msg, Kind, BasePath); } /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to /// DestType is possible and allowed. TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, bool CStyle, SourceRange OpRange, QualType OrigSrcType, QualType OrigDestType, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { // We can only work with complete types. But don't complain if it doesn't work if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || !Self.isCompleteType(OpRange.getBegin(), DestType)) return TC_NotApplicable; // Downcast can only happen in class hierarchies, so we need classes. if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { return TC_NotApplicable; } CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/true); if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { return TC_NotApplicable; } // Target type does derive from source type. Now we're serious. If an error // appears now, it's not ignored. // This may not be entirely in line with the standard. Take for example: // struct A {}; // struct B : virtual A { // B(A&); // }; // // void f() // { // (void)static_cast<const B&>(*((A*)0)); // } // As far as the standard is concerned, p5 does not apply (A is virtual), so // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. // However, both GCC and Comeau reject this example, and accepting it would // mean more complex code if we're to preserve the nice error message. // FIXME: Being 100% compliant here would be nice to have. // Must preserve cv, as always, unless we're in C-style mode. if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { msg = diag::err_bad_cxx_cast_qualifiers_away; return TC_Failed; } if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { // This code is analoguous to that in CheckDerivedToBaseConversion, except // that it builds the paths in reverse order. // To sum up: record all paths to the base and build a nice string from // them. Use it to spice up the error message. if (!Paths.isRecordingPaths()) { Paths.clear(); Paths.setRecordingPaths(true); Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); } std::string PathDisplayStr; std::set<unsigned> DisplayedPaths; for (clang::CXXBasePath &Path : Paths) { if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) { // We haven't displayed a path to this particular base // class subobject yet. PathDisplayStr += "\n "; for (CXXBasePathElement &PE : llvm::reverse(Path)) PathDisplayStr += PE.Base->getType().getAsString() + " -> "; PathDisplayStr += QualType(DestType).getAsString(); } } Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) << QualType(SrcType).getUnqualifiedType() << QualType(DestType).getUnqualifiedType() << PathDisplayStr << OpRange; msg = 0; return TC_Failed; } if (Paths.getDetectedVirtual() != nullptr) { QualType VirtualBase(Paths.getDetectedVirtual(), 0); Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) << OrigSrcType << OrigDestType << VirtualBase << OpRange; msg = 0; return TC_Failed; } if (!CStyle) { switch (Self.CheckBaseClassAccess(OpRange.getBegin(), SrcType, DestType, Paths.front(), diag::err_downcast_from_inaccessible_base)) { case Sema::AR_accessible: case Sema::AR_delayed: // be optimistic case Sema::AR_dependent: // be optimistic break; case Sema::AR_inaccessible: msg = 0; return TC_Failed; } } Self.BuildBasePathArray(Paths, BasePath); Kind = CK_BaseToDerived; return TC_Success; } /// TryStaticMemberPointerUpcast - Tests whether a conversion according to /// C++ 5.2.9p9 is valid: /// /// An rvalue of type "pointer to member of D of type cv1 T" can be /// converted to an rvalue of type "pointer to member of B of type cv2 T", /// where B is a base class of D [...]. /// TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); if (!DestMemPtr) return TC_NotApplicable; bool WasOverloadedFunction = false; DeclAccessPair FoundOverload; if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { if (FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, FoundOverload)) { CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); SrcType = Self.Context.getMemberPointerType(Fn->getType(), Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); WasOverloadedFunction = true; } } const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); if (!SrcMemPtr) { msg = diag::err_bad_static_cast_member_pointer_nonmp; return TC_NotApplicable; } // Lock down the inheritance model right now in MS ABI, whether or not the // pointee types are the same. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { (void)Self.isCompleteType(OpRange.getBegin(), SrcType); (void)Self.isCompleteType(OpRange.getBegin(), DestType); } // T == T, modulo cv if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), DestMemPtr->getPointeeType())) return TC_NotApplicable; // B base of D QualType SrcClass(SrcMemPtr->getClass(), 0); QualType DestClass(DestMemPtr->getClass(), 0); CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/true); if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) return TC_NotApplicable; // B is a base of D. But is it an allowed base? If not, it's a hard error. if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { Paths.clear(); Paths.setRecordingPaths(true); bool StillOkay = Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); assert(StillOkay); (void)StillOkay; std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; msg = 0; return TC_Failed; } if (const RecordType *VBase = Paths.getDetectedVirtual()) { Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) << SrcClass << DestClass << QualType(VBase, 0) << OpRange; msg = 0; return TC_Failed; } if (!CStyle) { switch (Self.CheckBaseClassAccess(OpRange.getBegin(), DestClass, SrcClass, Paths.front(), diag::err_upcast_to_inaccessible_base)) { case Sema::AR_accessible: case Sema::AR_delayed: case Sema::AR_dependent: // Optimistically assume that the delayed and dependent cases // will work out. break; case Sema::AR_inaccessible: msg = 0; return TC_Failed; } } if (WasOverloadedFunction) { // Resolve the address of the overloaded function again, this time // allowing complaints if something goes wrong. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, true, FoundOverload); if (!Fn) { msg = 0; return TC_Failed; } SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); if (!SrcExpr.isUsable()) { msg = 0; return TC_Failed; } } Self.BuildBasePathArray(Paths, BasePath); Kind = CK_DerivedToBaseMemberPointer; return TC_Success; } /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 /// is valid: /// /// An expression e can be explicitly converted to a type T using a /// @c static_cast if the declaration "T t(e);" is well-formed [...]. TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization) { if (DestType->isRecordType()) { if (Self.RequireCompleteType(OpRange.getBegin(), DestType, diag::err_bad_cast_incomplete) || Self.RequireNonAbstractType(OpRange.getBegin(), DestType, diag::err_allocation_of_abstract_type)) { msg = 0; return TC_Failed; } } InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); InitializationKind InitKind = (CCK == Sema::CCK_CStyleCast) ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, ListInitialization) : (CCK == Sema::CCK_FunctionalCast) ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) : InitializationKind::CreateCast(OpRange); Expr *SrcExprRaw = SrcExpr.get(); // FIXME: Per DR242, we should check for an implicit conversion sequence // or for a constructor that could be invoked by direct-initialization // here, not for an initialization sequence. InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); // At this point of CheckStaticCast, if the destination is a reference, // or the expression is an overload expression this has to work. // There is no other way that works. // On the other hand, if we're checking a C-style cast, we've still got // the reinterpret_cast way. bool CStyle = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) return TC_NotApplicable; ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); if (Result.isInvalid()) { msg = 0; return TC_Failed; } if (InitSeq.isConstructorInitialization()) Kind = CK_ConstructorConversion; else Kind = CK_NoOp; SrcExpr = Result; return TC_Success; } /// TryConstCast - See if a const_cast from source to destination is allowed, /// and perform it if it is. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, unsigned &msg) { DestType = Self.Context.getCanonicalType(DestType); QualType SrcType = SrcExpr.get()->getType(); bool NeedToMaterializeTemporary = false; if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { // C++11 5.2.11p4: // if a pointer to T1 can be explicitly converted to the type "pointer to // T2" using a const_cast, then the following conversions can also be // made: // -- an lvalue of type T1 can be explicitly converted to an lvalue of // type T2 using the cast const_cast<T2&>; // -- a glvalue of type T1 can be explicitly converted to an xvalue of // type T2 using the cast const_cast<T2&&>; and // -- if T1 is a class type, a prvalue of type T1 can be explicitly // converted to an xvalue of type T2 using the cast const_cast<T2&&>. if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { // Cannot const_cast non-lvalue to lvalue reference type. But if this // is C-style, static_cast might find a way, so we simply suggest a // message and tell the parent to keep searching. msg = diag::err_bad_cxx_cast_rvalue; return TC_NotApplicable; } if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) { if (!SrcType->isRecordType()) { // Cannot const_cast non-class prvalue to rvalue reference type. But if // this is C-style, static_cast can do this. msg = diag::err_bad_cxx_cast_rvalue; return TC_NotApplicable; } // Materialize the class prvalue so that the const_cast can bind a // reference to it. NeedToMaterializeTemporary = true; } // It's not completely clear under the standard whether we can // const_cast bit-field gl-values. Doing so would not be // intrinsically complicated, but for now, we say no for // consistency with other compilers and await the word of the // committee. if (SrcExpr.get()->refersToBitField()) { msg = diag::err_bad_cxx_cast_bitfield; return TC_NotApplicable; } DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); SrcType = Self.Context.getPointerType(SrcType); } // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] // the rules for const_cast are the same as those used for pointers. if (!DestType->isPointerType() && !DestType->isMemberPointerType() && !DestType->isObjCObjectPointerType()) { // Cannot cast to non-pointer, non-reference type. Note that, if DestType // was a reference type, we converted it to a pointer above. // The status of rvalue references isn't entirely clear, but it looks like // conversion to them is simply invalid. // C++ 5.2.11p3: For two pointer types [...] if (!CStyle) msg = diag::err_bad_const_cast_dest; return TC_NotApplicable; } if (DestType->isFunctionPointerType() || DestType->isMemberFunctionPointerType()) { // Cannot cast direct function pointers. // C++ 5.2.11p2: [...] where T is any object type or the void type [...] // T is the ultimate pointee of source and target type. if (!CStyle) msg = diag::err_bad_const_cast_dest; return TC_NotApplicable; } // C++ [expr.const.cast]p3: // "For two similar types T1 and T2, [...]" // // We only allow a const_cast to change cvr-qualifiers, not other kinds of // type qualifiers. (Likewise, we ignore other changes when determining // whether a cast casts away constness.) if (!Self.Context.hasCvrSimilarType(SrcType, DestType)) return TC_NotApplicable; if (NeedToMaterializeTemporary) // This is a const_cast from a class prvalue to an rvalue reference type. // Materialize a temporary to store the result of the conversion. SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(), SrcExpr.get(), /*IsLValueReference*/ false); return TC_Success; } // Checks for undefined behavior in reinterpret_cast. // The cases that is checked for is: // *reinterpret_cast<T*>(&a) // reinterpret_cast<T&>(a) // where accessing 'a' as type 'T' will result in undefined behavior. void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range) { unsigned DiagID = IsDereference ? diag::warn_pointer_indirection_from_incompatible_type : diag::warn_undefined_reinterpret_cast; if (Diags.isIgnored(DiagID, Range.getBegin())) return; QualType SrcTy, DestTy; if (IsDereference) { if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { return; } SrcTy = SrcType->getPointeeType(); DestTy = DestType->getPointeeType(); } else { if (!DestType->getAs<ReferenceType>()) { return; } SrcTy = SrcType; DestTy = DestType->getPointeeType(); } // Cast is compatible if the types are the same. if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { return; } // or one of the types is a char or void type if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { return; } // or one of the types is a tag type. if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { return; } // FIXME: Scoped enums? if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { return; } } Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; } static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, QualType DestType) { QualType SrcType = SrcExpr.get()->getType(); if (Self.Context.hasSameType(SrcType, DestType)) return; if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) if (SrcPtrTy->isObjCSelType()) { QualType DT = DestType; if (isa<PointerType>(DestType)) DT = DestType->getPointeeType(); if (!DT.getUnqualifiedType()->isVoidType()) Self.Diag(SrcExpr.get()->getExprLoc(), diag::warn_cast_pointer_from_sel) << SrcType << DestType << SrcExpr.get()->getSourceRange(); } } /// Diagnose casts that change the calling convention of a pointer to a function /// defined in the current TU. static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, QualType DstType, SourceRange OpRange) { // Check if this cast would change the calling convention of a function // pointer type. QualType SrcType = SrcExpr.get()->getType(); if (Self.Context.hasSameType(SrcType, DstType) || !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType()) return; const auto *SrcFTy = SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); const auto *DstFTy = DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); CallingConv SrcCC = SrcFTy->getCallConv(); CallingConv DstCC = DstFTy->getCallConv(); if (SrcCC == DstCC) return; // We have a calling convention cast. Check if the source is a pointer to a // known, specific function that has already been defined. Expr *Src = SrcExpr.get()->IgnoreParenImpCasts(); if (auto *UO = dyn_cast<UnaryOperator>(Src)) if (UO->getOpcode() == UO_AddrOf) Src = UO->getSubExpr()->IgnoreParenImpCasts(); auto *DRE = dyn_cast<DeclRefExpr>(Src); if (!DRE) return; auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); if (!FD) return; // Only warn if we are casting from the default convention to a non-default // convention. This can happen when the programmer forgot to apply the calling // convention to the function declaration and then inserted this cast to // satisfy the type system. CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention( FD->isVariadic(), FD->isCXXInstanceMember()); if (DstCC == DefaultCC || SrcCC != DefaultCC) return; // Diagnose this cast, as it is probably bad. StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC); StringRef DstCCName = FunctionType::getNameForCallConv(DstCC); Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv) << SrcCCName << DstCCName << OpRange; // The checks above are cheaper than checking if the diagnostic is enabled. // However, it's worth checking if the warning is enabled before we construct // a fixit. if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin())) return; // Try to suggest a fixit to change the calling convention of the function // whose address was taken. Try to use the latest macro for the convention. // For example, users probably want to write "WINAPI" instead of "__stdcall" // to match the Windows header declarations. SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc(); Preprocessor &PP = Self.getPreprocessor(); SmallVector<TokenValue, 6> AttrTokens; SmallString<64> CCAttrText; llvm::raw_svector_ostream OS(CCAttrText); if (Self.getLangOpts().MicrosoftExt) { // __stdcall or __vectorcall OS << "__" << DstCCName; IdentifierInfo *II = PP.getIdentifierInfo(OS.str()); AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) ? TokenValue(II->getTokenID()) : TokenValue(II)); } else { // __attribute__((stdcall)) or __attribute__((vectorcall)) OS << "__attribute__((" << DstCCName << "))"; AttrTokens.push_back(tok::kw___attribute); AttrTokens.push_back(tok::l_paren); AttrTokens.push_back(tok::l_paren); IdentifierInfo *II = PP.getIdentifierInfo(DstCCName); AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) ? TokenValue(II->getTokenID()) : TokenValue(II)); AttrTokens.push_back(tok::r_paren); AttrTokens.push_back(tok::r_paren); } StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens); if (!AttrSpelling.empty()) CCAttrText = AttrSpelling; OS << ' '; Self.Diag(NameLoc, diag::note_change_calling_conv_fixit) << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText); } static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange, const Expr *SrcExpr, QualType DestType, Sema &Self) { QualType SrcType = SrcExpr->getType(); // Not warning on reinterpret_cast, boolean, constant expressions, etc // are not explicit design choices, but consistent with GCC's behavior. // Feel free to modify them if you've reason/evidence for an alternative. if (CStyle && SrcType->isIntegralType(Self.Context) && !SrcType->isBooleanType() && !SrcType->isEnumeralType() && !SrcExpr->isIntegerConstantExpr(Self.Context) && Self.Context.getTypeSize(DestType) > Self.Context.getTypeSize(SrcType)) { // Separate between casts to void* and non-void* pointers. // Some APIs use (abuse) void* for something like a user context, // and often that value is an integer even if it isn't a pointer itself. // Having a separate warning flag allows users to control the warning // for their workflow. unsigned Diag = DestType->isVoidPointerType() ? diag::warn_int_to_void_pointer_cast : diag::warn_int_to_pointer_cast; Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; } } static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, ExprResult &Result) { // We can only fix an overloaded reinterpret_cast if // - it is a template with explicit arguments that resolves to an lvalue // unambiguously, or // - it is the only function in an overload set that may have its address // taken. Expr *E = Result.get(); // TODO: what if this fails because of DiagnoseUseOfDecl or something // like it? if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( Result, Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr ) && Result.isUsable()) return true; // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization // preserves Result. Result = E; if (!Self.resolveAndFixAddressOfSingleOverloadCandidate( Result, /*DoFunctionPointerConversion=*/true)) return false; return Result.isUsable(); } static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind) { bool IsLValueCast = false; DestType = Self.Context.getCanonicalType(DestType); QualType SrcType = SrcExpr.get()->getType(); // Is the source an overloaded name? (i.e. &foo) // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) if (SrcType == Self.Context.OverloadTy) { ExprResult FixedExpr = SrcExpr; if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) return TC_NotApplicable; assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr"); SrcExpr = FixedExpr; SrcType = SrcExpr.get()->getType(); } if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { if (!SrcExpr.get()->isGLValue()) { // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the // similar comment in const_cast. msg = diag::err_bad_cxx_cast_rvalue; return TC_NotApplicable; } if (!CStyle) { Self.CheckCompatibleReinterpretCast(SrcType, DestType, /*IsDereference=*/false, OpRange); } // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the // same effect as the conversion *reinterpret_cast<T*>(&x) with the // built-in & and * operators. const char *inappropriate = nullptr; switch (SrcExpr.get()->getObjectKind()) { case OK_Ordinary: break; case OK_BitField: msg = diag::err_bad_cxx_cast_bitfield; return TC_NotApplicable; // FIXME: Use a specific diagnostic for the rest of these cases. case OK_VectorComponent: inappropriate = "vector element"; break; case OK_MatrixComponent: inappropriate = "matrix element"; break; case OK_ObjCProperty: inappropriate = "property expression"; break; case OK_ObjCSubscript: inappropriate = "container subscripting expression"; break; } if (inappropriate) { Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) << inappropriate << DestType << OpRange << SrcExpr.get()->getSourceRange(); msg = 0; SrcExpr = ExprError(); return TC_NotApplicable; } // This code does this transformation for the checked types. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); SrcType = Self.Context.getPointerType(SrcType); IsLValueCast = true; } // Canonicalize source for comparison. SrcType = Self.Context.getCanonicalType(SrcType); const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), *SrcMemPtr = SrcType->getAs<MemberPointerType>(); if (DestMemPtr && SrcMemPtr) { // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" // can be explicitly converted to an rvalue of type "pointer to member // of Y of type T2" if T1 and T2 are both function types or both object // types. if (DestMemPtr->isMemberFunctionPointer() != SrcMemPtr->isMemberFunctionPointer()) return TC_NotApplicable; if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { // We need to determine the inheritance model that the class will use if // haven't yet. (void)Self.isCompleteType(OpRange.getBegin(), SrcType); (void)Self.isCompleteType(OpRange.getBegin(), DestType); } // Don't allow casting between member pointers of different sizes. if (Self.Context.getTypeSize(DestMemPtr) != Self.Context.getTypeSize(SrcMemPtr)) { msg = diag::err_bad_cxx_cast_member_pointer_size; return TC_Failed; } // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away // constness. // A reinterpret_cast followed by a const_cast can, though, so in C-style, // we accept it. if (auto CACK = CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, /*CheckObjCLifetime=*/CStyle)) return getCastAwayConstnessCastKind(CACK, msg); // A valid member pointer cast. assert(!IsLValueCast); Kind = CK_ReinterpretMemberPointer; return TC_Success; } // See below for the enumeral issue. if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral // type large enough to hold it. A value of std::nullptr_t can be // converted to an integral type; the conversion has the same meaning // and validity as a conversion of (void*)0 to the integral type. if (Self.Context.getTypeSize(SrcType) > Self.Context.getTypeSize(DestType)) { msg = diag::err_bad_reinterpret_cast_small_int; return TC_Failed; } Kind = CK_PointerToIntegral; return TC_Success; } // Allow reinterpret_casts between vectors of the same size and // between vectors and integers of the same size. bool destIsVector = DestType->isVectorType(); bool srcIsVector = SrcType->isVectorType(); if (srcIsVector || destIsVector) { // The non-vector type, if any, must have integral type. This is // the same rule that C vector casts use; note, however, that enum // types are not integral in C++. if ((!destIsVector && !DestType->isIntegralType(Self.Context)) || (!srcIsVector && !SrcType->isIntegralType(Self.Context))) return TC_NotApplicable; // The size we want to consider is eltCount * eltSize. // That's exactly what the lax-conversion rules will check. if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { Kind = CK_BitCast; return TC_Success; } // Otherwise, pick a reasonable diagnostic. if (!destIsVector) msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; else if (!srcIsVector) msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; else msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; return TC_Failed; } if (SrcType == DestType) { // C++ 5.2.10p2 has a note that mentions that, subject to all other // restrictions, a cast to the same type is allowed so long as it does not // cast away constness. In C++98, the intent was not entirely clear here, // since all other paragraphs explicitly forbid casts to the same type. // C++11 clarifies this case with p2. // // The only allowed types are: integral, enumeration, pointer, or // pointer-to-member types. We also won't restrict Obj-C pointers either. Kind = CK_NoOp; TryCastResult Result = TC_NotApplicable; if (SrcType->isIntegralOrEnumerationType() || SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) { Result = TC_Success; } return Result; } bool destIsPtr = DestType->isAnyPointerType() || DestType->isBlockPointerType(); bool srcIsPtr = SrcType->isAnyPointerType() || SrcType->isBlockPointerType(); if (!destIsPtr && !srcIsPtr) { // Except for std::nullptr_t->integer and lvalue->reference, which are // handled above, at least one of the two arguments must be a pointer. return TC_NotApplicable; } if (DestType->isIntegralType(Self.Context)) { assert(srcIsPtr && "One type must be a pointer"); // C++ 5.2.10p4: A pointer can be explicitly converted to any integral // type large enough to hold it; except in Microsoft mode, where the // integral type size doesn't matter (except we don't allow bool). if ((Self.Context.getTypeSize(SrcType) > Self.Context.getTypeSize(DestType))) { bool MicrosoftException = Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType(); if (MicrosoftException) { unsigned Diag = SrcType->isVoidPointerType() ? diag::warn_void_pointer_to_int_cast : diag::warn_pointer_to_int_cast; Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; } else { msg = diag::err_bad_reinterpret_cast_small_int; return TC_Failed; } } Kind = CK_PointerToIntegral; return TC_Success; } if (SrcType->isIntegralOrEnumerationType()) { assert(destIsPtr && "One type must be a pointer"); checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self); // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly // converted to a pointer. // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not // necessarily converted to a null pointer value.] Kind = CK_IntegralToPointer; return TC_Success; } if (!destIsPtr || !srcIsPtr) { // With the valid non-pointer conversions out of the way, we can be even // more stringent. return TC_NotApplicable; } // Cannot convert between block pointers and Objective-C object pointers. if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) return TC_NotApplicable; // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. // The C-style cast operator can. TryCastResult SuccessResult = TC_Success; if (auto CACK = CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, /*CheckObjCLifetime=*/CStyle)) SuccessResult = getCastAwayConstnessCastKind(CACK, msg); if (IsAddressSpaceConversion(SrcType, DestType)) { Kind = CK_AddressSpaceConversion; assert(SrcType->isPointerType() && DestType->isPointerType()); if (!CStyle && !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf( SrcType->getPointeeType().getQualifiers())) { SuccessResult = TC_Failed; } } else if (IsLValueCast) { Kind = CK_LValueBitCast; } else if (DestType->isObjCObjectPointerType()) { Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); } else if (DestType->isBlockPointerType()) { if (!SrcType->isBlockPointerType()) { Kind = CK_AnyPointerToBlockPointerCast; } else { Kind = CK_BitCast; } } else { Kind = CK_BitCast; } // Any pointer can be cast to an Objective-C pointer type with a C-style // cast. if (CStyle && DestType->isObjCObjectPointerType()) { return SuccessResult; } if (CStyle) DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); // Not casting away constness, so the only remaining check is for compatible // pointer categories. if (SrcType->isFunctionPointerType()) { if (DestType->isFunctionPointerType()) { // C++ 5.2.10p6: A pointer to a function can be explicitly converted to // a pointer to a function of a different type. return SuccessResult; } // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to // an object type or vice versa is conditionally-supported. // Compilers support it in C++03 too, though, because it's necessary for // casting the return value of dlsym() and GetProcAddress(). // FIXME: Conditionally-supported behavior should be configurable in the // TargetInfo or similar. Self.Diag(OpRange.getBegin(), Self.getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) << OpRange; return SuccessResult; } if (DestType->isFunctionPointerType()) { // See above. Self.Diag(OpRange.getBegin(), Self.getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) << OpRange; return SuccessResult; } // Diagnose address space conversion in nested pointers. QualType DestPtee = DestType->getPointeeType().isNull() ? DestType->getPointeeType() : DestType->getPointeeType()->getPointeeType(); QualType SrcPtee = SrcType->getPointeeType().isNull() ? SrcType->getPointeeType() : SrcType->getPointeeType()->getPointeeType(); while (!DestPtee.isNull() && !SrcPtee.isNull()) { if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) { Self.Diag(OpRange.getBegin(), diag::warn_bad_cxx_cast_nested_pointer_addr_space) << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange(); break; } DestPtee = DestPtee->getPointeeType(); SrcPtee = SrcPtee->getPointeeType(); } // C++ 5.2.10p7: A pointer to an object can be explicitly converted to // a pointer to an object of different type. // Void pointers are not specified, but supported by every compiler out there. // So we finish by allowing everything that remains - it's got to be two // object pointers. return SuccessResult; } static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, unsigned &msg, CastKind &Kind) { if (!Self.getLangOpts().OpenCL) // FIXME: As compiler doesn't have any information about overlapping addr // spaces at the moment we have to be permissive here. return TC_NotApplicable; // Even though the logic below is general enough and can be applied to // non-OpenCL mode too, we fast-path above because no other languages // define overlapping address spaces currently. auto SrcType = SrcExpr.get()->getType(); // FIXME: Should this be generalized to references? The reference parameter // however becomes a reference pointee type here and therefore rejected. // Perhaps this is the right behavior though according to C++. auto SrcPtrType = SrcType->getAs<PointerType>(); if (!SrcPtrType) return TC_NotApplicable; auto DestPtrType = DestType->getAs<PointerType>(); if (!DestPtrType) return TC_NotApplicable; auto SrcPointeeType = SrcPtrType->getPointeeType(); auto DestPointeeType = DestPtrType->getPointeeType(); if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) { msg = diag::err_bad_cxx_cast_addr_space_mismatch; return TC_Failed; } auto SrcPointeeTypeWithoutAS = Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType()); auto DestPointeeTypeWithoutAS = Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType()); if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS, DestPointeeTypeWithoutAS)) { Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace() ? CK_NoOp : CK_AddressSpaceConversion; return TC_Success; } else { return TC_NotApplicable; } } void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) { // In OpenCL only conversions between pointers to objects in overlapping // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps // with any named one, except for constant. // Converting the top level pointee addrspace is permitted for compatible // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but // if any of the nested pointee addrspaces differ, we emit a warning // regardless of addrspace compatibility. This makes // local int ** p; // return (generic int **) p; // warn even though local -> generic is permitted. if (Self.getLangOpts().OpenCL) { const Type *DestPtr, *SrcPtr; bool Nested = false; unsigned DiagID = diag::err_typecheck_incompatible_address_space; DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()), SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr()); while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) { const PointerType *DestPPtr = cast<PointerType>(DestPtr); const PointerType *SrcPPtr = cast<PointerType>(SrcPtr); QualType DestPPointee = DestPPtr->getPointeeType(); QualType SrcPPointee = SrcPPtr->getPointeeType(); if (Nested ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace() : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) { Self.Diag(OpRange.getBegin(), DiagID) << SrcType << DestType << Sema::AA_Casting << SrcExpr.get()->getSourceRange(); if (!Nested) SrcExpr = ExprError(); return; } DestPtr = DestPPtr->getPointeeType().getTypePtr(); SrcPtr = SrcPPtr->getPointeeType().getTypePtr(); Nested = true; DiagID = diag::ext_nested_pointer_qualifier_mismatch; } } } void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, bool ListInitialization) { assert(Self.getLangOpts().CPlusPlus); // Handle placeholders. if (isPlaceholder()) { // C-style casts can resolve __unknown_any types. if (claimPlaceholder(BuiltinType::UnknownAny)) { SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, SrcExpr.get(), Kind, ValueKind, BasePath); return; } checkNonOverloadPlaceholders(); if (SrcExpr.isInvalid()) return; } // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". // This test is outside everything else because it's the only case where // a non-lvalue-reference target type does not lead to decay. if (DestType->isVoidType()) { Kind = CK_ToVoid; if (claimPlaceholder(BuiltinType::Overload)) { Self.ResolveAndFixSingleFunctionTemplateSpecialization( SrcExpr, /* Decay Function to ptr */ false, /* Complain */ true, DestRange, DestType, diag::err_bad_cstyle_cast_overload); if (SrcExpr.isInvalid()) return; } SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); return; } // If the type is dependent, we won't do any other semantic analysis now. if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || SrcExpr.get()->isValueDependent()) { assert(Kind == CK_Dependent); return; } if (ValueKind == VK_RValue && !DestType->isRecordType() && !isPlaceholder(BuiltinType::Overload)) { SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); if (SrcExpr.isInvalid()) return; } // AltiVec vector initialization with a single literal. if (const VectorType *vecTy = DestType->getAs<VectorType>()) if (vecTy->getVectorKind() == VectorType::AltiVecVector && (SrcExpr.get()->getType()->isIntegerType() || SrcExpr.get()->getType()->isFloatingType())) { Kind = CK_VectorSplat; SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); return; } // C++ [expr.cast]p5: The conversions performed by // - a const_cast, // - a static_cast, // - a static_cast followed by a const_cast, // - a reinterpret_cast, or // - a reinterpret_cast followed by a const_cast, // can be performed using the cast notation of explicit type conversion. // [...] If a conversion can be interpreted in more than one of the ways // listed above, the interpretation that appears first in the list is used, // even if a cast resulting from that interpretation is ill-formed. // In plain language, this means trying a const_cast ... // Note that for address space we check compatibility after const_cast. unsigned msg = diag::err_bad_cxx_cast_generic; TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg); if (SrcExpr.isInvalid()) return; if (isValidCast(tcr)) Kind = CK_NoOp; Sema::CheckedConversionKind CCK = FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast; if (tcr == TC_NotApplicable) { tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg, Kind); if (SrcExpr.isInvalid()) return; if (tcr == TC_NotApplicable) { // ... or if that is not possible, a static_cast, ignoring const and // addr space, ... tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization); if (SrcExpr.isInvalid()) return; if (tcr == TC_NotApplicable) { // ... and finally a reinterpret_cast, ignoring const and addr space. tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true, OpRange, msg, Kind); if (SrcExpr.isInvalid()) return; } } } if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && isValidCast(tcr)) checkObjCConversion(CCK); if (tcr != TC_Success && msg != 0) { if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { DeclAccessPair Found; FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, /*Complain*/ true, Found); if (Fn) { // If DestType is a function type (not to be confused with the function // pointer type), it will be possible to resolve the function address, // but the type cast should be considered as failure. OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) << OE->getName() << DestType << OpRange << OE->getQualifierLoc().getSourceRange(); Self.NoteAllOverloadCandidates(SrcExpr.get()); } } else { diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), OpRange, SrcExpr.get(), DestType, ListInitialization); } } if (isValidCast(tcr)) { if (Kind == CK_BitCast) checkCastAlign(); } else { SrcExpr = ExprError(); } } /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a /// non-matching type. Such as enum function call to int, int call to /// pointer; etc. Cast to 'void' is an exception. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, QualType DestType) { if (Self.Diags.isIgnored(diag::warn_bad_function_cast, SrcExpr.get()->getExprLoc())) return; if (!isa<CallExpr>(SrcExpr.get())) return; QualType SrcType = SrcExpr.get()->getType(); if (DestType.getUnqualifiedType()->isVoidType()) return; if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) return; if (SrcType->isIntegerType() && DestType->isIntegerType() && (SrcType->isBooleanType() == DestType->isBooleanType()) && (SrcType->isEnumeralType() == DestType->isEnumeralType())) return; if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) return; if (SrcType->isEnumeralType() && DestType->isEnumeralType()) return; if (SrcType->isComplexType() && DestType->isComplexType()) return; if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) return; if (SrcType->isFixedPointType() && DestType->isFixedPointType()) return; Self.Diag(SrcExpr.get()->getExprLoc(), diag::warn_bad_function_cast) << SrcType << DestType << SrcExpr.get()->getSourceRange(); } /// Check the semantics of a C-style cast operation, in C. void CastOperation::CheckCStyleCast() { assert(!Self.getLangOpts().CPlusPlus); // C-style casts can resolve __unknown_any types. if (claimPlaceholder(BuiltinType::UnknownAny)) { SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, SrcExpr.get(), Kind, ValueKind, BasePath); return; } // C99 6.5.4p2: the cast type needs to be void or scalar and the expression // type needs to be scalar. if (DestType->isVoidType()) { // We don't necessarily do lvalue-to-rvalue conversions on this. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); if (SrcExpr.isInvalid()) return; // Cast to void allows any expr type. Kind = CK_ToVoid; return; } // Overloads are allowed with C extensions, so we need to support them. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { DeclAccessPair DAP; if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( SrcExpr.get(), DestType, /*Complain=*/true, DAP)) SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); else return; assert(SrcExpr.isUsable()); } SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); if (SrcExpr.isInvalid()) return; QualType SrcType = SrcExpr.get()->getType(); assert(!SrcType->isPlaceholderType()); checkAddressSpaceCast(SrcType, DestType); if (SrcExpr.isInvalid()) return; if (Self.RequireCompleteType(OpRange.getBegin(), DestType, diag::err_typecheck_cast_to_incomplete)) { SrcExpr = ExprError(); return; } // Allow casting a sizeless built-in type to itself. if (DestType->isSizelessBuiltinType() && Self.Context.hasSameUnqualifiedType(DestType, SrcType)) { Kind = CK_NoOp; return; } if (!DestType->isScalarType() && !DestType->isVectorType()) { const RecordType *DestRecordTy = DestType->getAs<RecordType>(); if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ // GCC struct/union extension: allow cast to self. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) << DestType << SrcExpr.get()->getSourceRange(); Kind = CK_NoOp; return; } // GCC's cast to union extension. if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { RecordDecl *RD = DestRecordTy->getDecl(); if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) { Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) << SrcExpr.get()->getSourceRange(); Kind = CK_ToUnion; return; } else { Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) << SrcType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type. if (Self.getLangOpts().OpenCL && DestType->isEventT()) { Expr::EvalResult Result; if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) { llvm::APSInt CastInt = Result.Val.getInt(); if (0 == CastInt) { Kind = CK_ZeroToOCLOpaqueType; return; } Self.Diag(OpRange.getBegin(), diag::err_opencl_cast_non_zero_to_event_t) << CastInt.toString(10) << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } // Reject any other conversions to non-scalar types. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) << DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } // The type we're casting to is known to be a scalar or vector. // Require the operand to be a scalar or vector. if (!SrcType->isScalarType() && !SrcType->isVectorType()) { Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_typecheck_expect_scalar_operand) << SrcType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } if (DestType->isExtVectorType()) { SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); return; } if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && (SrcType->isIntegerType() || SrcType->isFloatingType())) { Kind = CK_VectorSplat; SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { SrcExpr = ExprError(); } return; } if (SrcType->isVectorType()) { if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) SrcExpr = ExprError(); return; } // The source and target types are both scalars, i.e. // - arithmetic types (fundamental, enum, and complex) // - all kinds of pointers // Note that member pointers were filtered out with C++, above. if (isa<ObjCSelectorExpr>(SrcExpr.get())) { Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); SrcExpr = ExprError(); return; } // Can't cast to or from bfloat if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) { Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16) << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) { Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16) << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } // If either type is a pointer, the other type has to be either an // integer or a pointer. if (!DestType->isArithmeticType()) { if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_pointer_from_non_pointer_int) << SrcType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType, Self); } else if (!SrcType->isArithmeticType()) { if (!DestType->isIntegralType(Self.Context) && DestType->isArithmeticType()) { Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_cast_pointer_to_non_pointer_int) << DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } if ((Self.Context.getTypeSize(SrcType) > Self.Context.getTypeSize(DestType)) && !DestType->isBooleanType()) { // C 6.3.2.3p6: Any pointer type may be converted to an integer type. // Except as previously specified, the result is implementation-defined. // If the result cannot be represented in the integer type, the behavior // is undefined. The result need not be in the range of values of any // integer type. unsigned Diag; if (SrcType->isVoidPointerType()) Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast : diag::warn_void_pointer_to_int_cast; else if (DestType->isEnumeralType()) Diag = diag::warn_pointer_to_enum_cast; else Diag = diag::warn_pointer_to_int_cast; Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; } } if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) { if (DestType->isHalfType()) { Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half) << DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } // ARC imposes extra restrictions on casts. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) { checkObjCConversion(Sema::CCK_CStyleCast); if (SrcExpr.isInvalid()) return; const PointerType *CastPtr = DestType->getAs<PointerType>(); if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) { if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); if (CastPtr->getPointeeType()->isObjCLifetimeType() && ExprPtr->getPointeeType()->isObjCLifetimeType() && !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_typecheck_incompatible_ownership) << SrcType << DestType << Sema::AA_Casting << SrcExpr.get()->getSourceRange(); return; } } } else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); DiagnoseBadFunctionCast(Self, SrcExpr, DestType); Kind = Self.PrepareScalarCast(SrcExpr, DestType); if (SrcExpr.isInvalid()) return; if (Kind == CK_BitCast) checkCastAlign(); } void CastOperation::CheckBuiltinBitCast() { QualType SrcType = SrcExpr.get()->getType(); if (Self.RequireCompleteType(OpRange.getBegin(), DestType, diag::err_typecheck_cast_to_incomplete) || Self.RequireCompleteType(OpRange.getBegin(), SrcType, diag::err_incomplete_type)) { SrcExpr = ExprError(); return; } if (SrcExpr.get()->isRValue()) SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(), /*IsLValueReference=*/false); CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType); CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType); if (DestSize != SourceSize) { Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch) << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity(); SrcExpr = ExprError(); return; } if (!DestType.isTriviallyCopyableType(Self.Context)) { Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) << 1; SrcExpr = ExprError(); return; } if (!SrcType.isTriviallyCopyableType(Self.Context)) { Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) << 0; SrcExpr = ExprError(); return; } Kind = CK_LValueToRValueBitCast; } /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either /// const, volatile or both. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, QualType DestType) { if (SrcExpr.isInvalid()) return; QualType SrcType = SrcExpr.get()->getType(); if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) || DestType->isLValueReferenceType())) return; QualType TheOffendingSrcType, TheOffendingDestType; Qualifiers CastAwayQualifiers; if (CastsAwayConstness(Self, SrcType, DestType, true, false, &TheOffendingSrcType, &TheOffendingDestType, &CastAwayQualifiers) != CastAwayConstnessKind::CACK_Similar) return; // FIXME: 'restrict' is not properly handled here. int qualifiers = -1; if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { qualifiers = 0; } else if (CastAwayQualifiers.hasConst()) { qualifiers = 1; } else if (CastAwayQualifiers.hasVolatile()) { qualifiers = 2; } // This is a variant of int **x; const int **y = (const int **)x; if (qualifiers == -1) Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2) << SrcType << DestType; else Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual) << TheOffendingSrcType << TheOffendingDestType << qualifiers; } ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, TypeSourceInfo *CastTypeInfo, SourceLocation RPLoc, Expr *CastExpr) { CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc()); if (getLangOpts().CPlusPlus) { Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false, isa<InitListExpr>(CastExpr)); } else { Op.CheckCStyleCast(); } if (Op.SrcExpr.isInvalid()) return ExprError(); // -Wcast-qual DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType); Op.checkQualifiedDestType(); return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); } ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, QualType Type, SourceLocation LPLoc, Expr *CastExpr, SourceLocation RPLoc) { assert(LPLoc.isValid() && "List-initialization shouldn't get here."); CastOperation Op(*this, Type, CastExpr); Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc()); Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false); if (Op.SrcExpr.isInvalid()) return ExprError(); Op.checkQualifiedDestType(); auto *SubExpr = Op.SrcExpr.get(); if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) SubExpr = BindExpr->getSubExpr(); if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind, Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc)); }
// ===== push Argument 1 ===== @1 D=A @ARG A=M+D D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== pop Pointer 1 ====== @THAT D=A @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== push Constant 0 ===== @0 D=A @SP A=M M=D // SP++ @SP M=M+1 // ===== pop That 0 ====== @0 D=A @THAT D=M+D @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== push Constant 1 ===== @1 D=A @SP A=M M=D // SP++ @SP M=M+1 // ===== pop That 1 ====== @1 D=A @THAT D=M+D @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== push Argument 0 ===== @0 D=A @ARG A=M+D D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== push Constant 2 ===== @2 D=A @SP A=M M=D // SP++ @SP M=M+1 // ===== arithmetic command Sub ===== // SP-- @SP M=M-1 // D=Memory[SP] @SP A=M D=M // SP-- @SP M=M-1 // A=Memory[SP] A=M // Sub M=M-D // SP++ @SP M=M+1 // ===== pop Argument 0 ====== @0 D=A @ARG D=M+D @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== label MAIN_LOOP_START ====== (MAIN_LOOP_START) // ===== push Argument 0 ===== @0 D=A @ARG A=M+D D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== if-goto COMPUTE_ELEMENT ====== // SP-- @SP M=M-1 A=M D=M @COMPUTE_ELEMENT D;JGT // ===== goto END_PROGRAM ====== @END_PROGRAM 0;JMP // ===== label COMPUTE_ELEMENT ====== (COMPUTE_ELEMENT) // ===== push That 0 ===== @0 D=A @THAT A=M+D D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== push That 1 ===== @1 D=A @THAT A=M+D D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== arithmetic command Add ===== // SP-- @SP M=M-1 // D=Memory[SP] @SP A=M D=M // SP-- @SP M=M-1 // A=Memory[SP] A=M // Add M=M+D // SP++ @SP M=M+1 // ===== pop That 2 ====== @2 D=A @THAT D=M+D @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== push Pointer 1 ===== @THAT D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== push Constant 1 ===== @1 D=A @SP A=M M=D // SP++ @SP M=M+1 // ===== arithmetic command Add ===== // SP-- @SP M=M-1 // D=Memory[SP] @SP A=M D=M // SP-- @SP M=M-1 // A=Memory[SP] A=M // Add M=M+D // SP++ @SP M=M+1 // ===== pop Pointer 1 ====== @THAT D=A @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== push Argument 0 ===== @0 D=A @ARG A=M+D D=M @SP A=M M=D // SP++ @SP M=M+1 // ===== push Constant 1 ===== @1 D=A @SP A=M M=D // SP++ @SP M=M+1 // ===== arithmetic command Sub ===== // SP-- @SP M=M-1 // D=Memory[SP] @SP A=M D=M // SP-- @SP M=M-1 // A=Memory[SP] A=M // Sub M=M-D // SP++ @SP M=M+1 // ===== pop Argument 0 ====== @0 D=A @ARG D=M+D @R13 M=D // SP-- @SP M=M-1 A=M D=M @R13 A=M M=D // ===== goto MAIN_LOOP_START ====== @MAIN_LOOP_START 0;JMP // ===== label END_PROGRAM ====== (END_PROGRAM)
// // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdAttribute.h" #include "private/Utils.h" #ifdef UFE_V3_FEATURES_AVAILABLE #include <mayaUsd/base/tokens.h> #endif #include <mayaUsd/ufe/StagesSubject.h> #include <mayaUsd/ufe/Utils.h> #include <mayaUsd/undo/UsdUndoBlock.h> #include <mayaUsd/undo/UsdUndoableItem.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/attributeSpec.h> #include <pxr/usd/usd/schemaRegistry.h> #include <sstream> #include <unordered_map> #include <unordered_set> // Note: normally we would use this using directive, but here we cannot because // our class is called UsdAttribute which is exactly the same as the one // in USD. // PXR_NAMESPACE_USING_DIRECTIVE static constexpr char kErrorMsgFailedConvertToString[] = "Could not convert the attribute to a string"; static constexpr char kErrorMsgInvalidType[] = "USD attribute does not match created attribute class type"; #ifdef UFE_V3_FEATURES_AVAILABLE static constexpr char kErrorMsgInvalidValueType[] = "Unexpected Ufe::Value type"; #endif //------------------------------------------------------------------------------ // Helper functions //------------------------------------------------------------------------------ namespace { template <typename T> bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) { // USD Attribute Notification doubling problem: // As of 24-Nov-2019, calling Set() on a UsdAttribute causes two "info only" // change notifications to be sent (see StagesSubject::stageChanged). With // the current USD implementation (USD 19.11), UsdAttribute::Set() ends up // in UsdStage::_SetValueImpl(). This function calls in sequence: // - UsdStage::_CreateAttributeSpecForEditing(), which has an SdfChangeBlock // whose expiry causes a notification to be sent. // - SdfLayer::SetField(), which also has an SdfChangeBlock whose // expiry causes a notification to be sent. // These two calls appear to be made on all calls to UsdAttribute::Set(), // not just on the first call. // // Trying to wrap the call to UsdAttribute::Set() inside an additional // SdfChangeBlock fails: no notifications are sent at all. This is most // likely because of the warning given in the SdfChangeBlock documentation: // // https://graphics.pixar.com/usd/docs/api/class_sdf_change_block.html // // which stages that "it is not safe to use [...] [a] downstream API [such // as Usd] while a changeblock is open [...]". // // Therefore, we have implemented an attribute change block notification of // our own in the StagesSubject, which we invoke here, so that only a // single UFE attribute changed notification is generated. if (!attr.IsValid()) return false; MayaUsd::ufe::AttributeChangedNotificationGuard guard; std::string errMsg; bool isSetAttrAllowed = MayaUsd::ufe::isAttributeEditAllowed(attr, &errMsg); if (!isSetAttrAllowed) { throw std::runtime_error(errMsg); } return attr.Set<T>(value); } #ifdef UFE_V3_FEATURES_AVAILABLE bool setUsdAttrMetadata( const PXR_NS::UsdAttribute& attr, const std::string& key, const Ufe::Value& value) { // Special cases for known Ufe metadata keys. // Note: we allow the locking attribute to be changed even if attribute is locked // since that is how you unlock. if (key == Ufe::Attribute::kLocked) { return attr.SetMetadata( MayaUsdMetadata->Lock, value.get<bool>() ? MayaUsdTokens->On : MayaUsdTokens->Off); } // If attribute is locked don't allow setting Metadata. std::string errMsg; const bool isSetAttrAllowed = MayaUsd::ufe::isAttributeEditAllowed(attr, &errMsg); if (!isSetAttrAllowed) { throw std::runtime_error(errMsg); } // We must convert the Ufe::Value to VtValue for storage in Usd. // Figure out the type of the input Ufe Value and create proper Usd VtValue. PXR_NS::VtValue usdValue; if (value.isType<bool>()) usdValue = value.get<bool>(); else if (value.isType<int>()) usdValue = value.get<int>(); else if (value.isType<float>()) usdValue = value.get<float>(); else if (value.isType<double>()) usdValue = value.get<double>(); else if (value.isType<std::string>()) usdValue = value.get<std::string>(); else { TF_CODING_ERROR(kErrorMsgInvalidValueType); } if (!usdValue.IsEmpty()) { PXR_NS::TfToken tok(key); return attr.SetMetadata(tok, usdValue); } return false; } #endif PXR_NS::UsdTimeCode getCurrentTime(const Ufe::SceneItem::Ptr& item) { // Attributes with time samples will fail when calling Get with default time code. // So we'll always use the current time when calling Get. If there are no time // samples, it will fall-back to the default time code. return MayaUsd::ufe::getTime(item->path()); } std::string getUsdAttributeValueAsString(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { if (!attr.IsValid() || !attr.HasValue()) return std::string(); PXR_NS::VtValue v; if (attr.Get(&v, time)) { if (v.CanCast<std::string>()) { PXR_NS::VtValue v_str = v.Cast<std::string>(); return v_str.Get<std::string>(); } std::ostringstream os; os << v; return os.str(); } TF_CODING_ERROR(kErrorMsgFailedConvertToString); return std::string(); } template <typename T, typename U> U getUsdAttributeVectorAsUfe(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { if (!attr.IsValid() || !attr.HasValue()) return U(); PXR_NS::VtValue vt; if (attr.Get(&vt, time) && vt.IsHolding<T>()) { T gfVec = vt.UncheckedGet<T>(); U ret(gfVec[0], gfVec[1], gfVec[2]); return ret; } return U(); } template <typename T, typename U> void setUsdAttributeVectorFromUfe( PXR_NS::UsdAttribute& attr, const U& value, const PXR_NS::UsdTimeCode& time) { T vec; vec.Set(value.x(), value.y(), value.z()); setUsdAttr<T>(attr, vec); } class UsdUndoableCommand : public Ufe::UndoableCommand { public: void execute() override { MayaUsd::UsdUndoBlock undoBlock(&_undoableItem); executeUndoBlock(); } void undo() override { _undoableItem.undo(); } void redo() override { _undoableItem.redo(); } protected: // Actual implementation of the execution of the command, // executed "within" a UsdUndoBlock to capture undo data, // to be implemented by the sub-class. virtual void executeUndoBlock() = 0; private: MayaUsd::UsdUndoableItem _undoableItem; }; template <typename T, typename A = MayaUsd::ufe::TypedUsdAttribute<T>> class SetUndoableCommand : public UsdUndoableCommand { public: SetUndoableCommand(const typename A::Ptr& attr, const T& newValue) : _attr(attr) , _newValue(newValue) { } void executeUndoBlock() override { _attr->set(_newValue); } private: const typename A::Ptr _attr; const T _newValue; }; #ifdef UFE_V3_FEATURES_AVAILABLE class SetUndoableMetadataCommand : public UsdUndoableCommand { public: SetUndoableMetadataCommand( const PXR_NS::UsdAttribute& usdAttr, const std::string& key, const Ufe::Value& newValue) : _usdAttr(usdAttr) , _key(key) , _newValue(newValue) { } void executeUndoBlock() override { setUsdAttrMetadata(_usdAttr, _key, _newValue); } private: const PXR_NS::UsdAttribute _usdAttr; const std::string _key; const Ufe::Value _newValue; }; #endif } // end namespace namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // UsdAttribute: //------------------------------------------------------------------------------ UsdAttribute::UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : fUsdAttr(usdAttr) { fPrim = item->prim(); } UsdAttribute::~UsdAttribute() { } bool UsdAttribute::hasValue() const { return fUsdAttr.HasValue(); } std::string UsdAttribute::name() const { // Should be the same as the name we were created with. return fUsdAttr.GetName().GetString(); } std::string UsdAttribute::documentation() const { return fUsdAttr.GetDocumentation(); } std::string UsdAttribute::string(const Ufe::SceneItem::Ptr& item) const { return getUsdAttributeValueAsString(fUsdAttr, getCurrentTime(item)); } #ifdef UFE_V3_FEATURES_AVAILABLE Ufe::Value UsdAttribute::getMetadata(const std::string& key) const { // Special cases for known Ufe metadata keys. if (key == Ufe::Attribute::kLocked) { PXR_NS::TfToken lock; bool ret = fUsdAttr.GetMetadata(MayaUsdMetadata->Lock, &lock); if (ret) return Ufe::Value((lock == MayaUsdTokens->On) ? true : false); return Ufe::Value(); } PXR_NS::TfToken tok(key); PXR_NS::VtValue v; if (fUsdAttr.GetMetadata(tok, &v)) { if (v.IsHolding<bool>()) return Ufe::Value(v.Get<bool>()); else if (v.IsHolding<int>()) return Ufe::Value(v.Get<int>()); else if (v.IsHolding<float>()) return Ufe::Value(v.Get<float>()); else if (v.IsHolding<double>()) return Ufe::Value(v.Get<double>()); else if (v.IsHolding<std::string>()) return Ufe::Value(v.Get<std::string>()); else if (v.IsHolding<PXR_NS::TfToken>()) return Ufe::Value(v.Get<PXR_NS::TfToken>().GetString()); } return Ufe::Value(); } bool UsdAttribute::setMetadata(const std::string& key, const Ufe::Value& value) { return setUsdAttrMetadata(fUsdAttr, key, value); } Ufe::UndoableCommand::Ptr UsdAttribute::setMetadataCmd(const std::string& key, const Ufe::Value& value) { return std::make_shared<SetUndoableMetadataCommand>(fUsdAttr, key, value); } bool UsdAttribute::clearMetadata(const std::string& key) { // Special cases for known Ufe metadata keys. if (key == Ufe::Attribute::kLocked) { return fUsdAttr.ClearMetadata(MayaUsdMetadata->Lock); } PXR_NS::TfToken tok(key); return fUsdAttr.ClearMetadata(tok); } bool UsdAttribute::hasMetadata(const std::string& key) const { // Special cases for known Ufe metadata keys. if (key == Ufe::Attribute::kLocked) { return fUsdAttr.HasMetadata(MayaUsdMetadata->Lock); } PXR_NS::TfToken tok(key); return fUsdAttr.HasMetadata(tok); } #endif //------------------------------------------------------------------------------ // UsdAttributeGeneric: //------------------------------------------------------------------------------ UsdAttributeGeneric::UsdAttributeGeneric( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::AttributeGeneric(item) , UsdAttribute(item, usdAttr) { } /*static*/ UsdAttributeGeneric::Ptr UsdAttributeGeneric::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeGeneric>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeGeneric - Ufe::AttributeGeneric overrides //------------------------------------------------------------------------------ std::string UsdAttributeGeneric::nativeType() const { return fUsdAttr.GetTypeName().GetType().GetTypeName(); } //------------------------------------------------------------------------------ // UsdAttributeEnumString: //------------------------------------------------------------------------------ UsdAttributeEnumString::UsdAttributeEnumString( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::AttributeEnumString(item) , UsdAttribute(item, usdAttr) { } /*static*/ UsdAttributeEnumString::Ptr UsdAttributeEnumString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeEnumString>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeEnumString - Ufe::AttributeEnumString overrides //------------------------------------------------------------------------------ std::string UsdAttributeEnumString::get() const { PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem())) && vt.IsHolding<TfToken>()) { TfToken tok = vt.UncheckedGet<TfToken>(); return tok.GetString(); } return std::string(); } void UsdAttributeEnumString::set(const std::string& value) { PXR_NS::TfToken tok(value); setUsdAttr<PXR_NS::TfToken>(fUsdAttr, tok); } Ufe::UndoableCommand::Ptr UsdAttributeEnumString::setCmd(const std::string& value) { auto self = std::dynamic_pointer_cast<UsdAttributeEnumString>(shared_from_this()); if (!TF_VERIFY(self, kErrorMsgInvalidType)) return nullptr; std::string errMsg; if (!MayaUsd::ufe::isAttributeEditAllowed(fUsdAttr, &errMsg)) { MGlobal::displayError(errMsg.c_str()); return nullptr; } return std::make_shared<SetUndoableCommand<std::string, UsdAttributeEnumString>>(self, value); } Ufe::AttributeEnumString::EnumValues UsdAttributeEnumString::getEnumValues() const { PXR_NS::TfToken tk(name()); auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(tk); if (attrDefn && attrDefn->HasAllowedTokens()) { auto tokenArray = attrDefn->GetAllowedTokens(); std::vector<PXR_NS::TfToken> tokenVec(tokenArray.begin(), tokenArray.end()); EnumValues tokens = PXR_NS::TfToStringVector(tokenVec); return tokens; } return EnumValues(); } //------------------------------------------------------------------------------ // TypedUsdAttribute<T>: //------------------------------------------------------------------------------ template <typename T> TypedUsdAttribute<T>::TypedUsdAttribute( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::TypedAttribute<T>(item) , UsdAttribute(item, usdAttr) { } template <typename T> Ufe::UndoableCommand::Ptr TypedUsdAttribute<T>::setCmd(const T& value) { std::string errMsg; if (!MayaUsd::ufe::isAttributeEditAllowed(fUsdAttr, &errMsg)) { MGlobal::displayError(errMsg.c_str()); return nullptr; } // See // https://stackoverflow.com/questions/17853212/using-shared-from-this-in-templated-classes // for explanation of this->shared_from_this() in templated class. auto self = std::dynamic_pointer_cast<TypedUsdAttribute<T>>(this->shared_from_this()); return std::make_shared<SetUndoableCommand<T>>(self, value); } //------------------------------------------------------------------------------ // TypedUsdAttribute<T> - Ufe::TypedAttribute overrides //------------------------------------------------------------------------------ template <> std::string TypedUsdAttribute<std::string>::get() const { if (!hasValue()) return std::string(); PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem()))) { // The USDAttribute can be holding either TfToken or string. if (vt.IsHolding<TfToken>()) { TfToken tok = vt.UncheckedGet<TfToken>(); return tok.GetString(); } else if (vt.IsHolding<std::string>()) { return vt.UncheckedGet<std::string>(); } } return std::string(); } template <> void TypedUsdAttribute<std::string>::set(const std::string& value) { // We need to figure out if the USDAttribute is holding a TfToken or string. const PXR_NS::SdfValueTypeName typeName = fUsdAttr.GetTypeName(); if (typeName.GetHash() == SdfValueTypeNames->String.GetHash()) { setUsdAttr<std::string>(fUsdAttr, value); return; } else if (typeName.GetHash() == SdfValueTypeNames->Token.GetHash()) { PXR_NS::TfToken tok(value); setUsdAttr<PXR_NS::TfToken>(fUsdAttr, tok); return; } // If we get here it means the USDAttribute type wasn't TfToken or string. TF_CODING_ERROR(kErrorMsgInvalidType); } template <> Ufe::Color3f TypedUsdAttribute<Ufe::Color3f>::get() const { return getUsdAttributeVectorAsUfe<GfVec3f, Ufe::Color3f>(fUsdAttr, getCurrentTime(sceneItem())); } // Note: cannot use setUsdAttributeVectorFromUfe since it relies on x/y/z template <> void TypedUsdAttribute<Ufe::Color3f>::set(const Ufe::Color3f& value) { GfVec3f vec; vec.Set(value.r(), value.g(), value.b()); setUsdAttr<GfVec3f>(fUsdAttr, vec); } template <> Ufe::Vector3i TypedUsdAttribute<Ufe::Vector3i>::get() const { return getUsdAttributeVectorAsUfe<GfVec3i, Ufe::Vector3i>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3i>::set(const Ufe::Vector3i& value) { setUsdAttributeVectorFromUfe<GfVec3i, Ufe::Vector3i>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <> Ufe::Vector3f TypedUsdAttribute<Ufe::Vector3f>::get() const { return getUsdAttributeVectorAsUfe<GfVec3f, Ufe::Vector3f>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3f>::set(const Ufe::Vector3f& value) { setUsdAttributeVectorFromUfe<GfVec3f, Ufe::Vector3f>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <> Ufe::Vector3d TypedUsdAttribute<Ufe::Vector3d>::get() const { return getUsdAttributeVectorAsUfe<GfVec3d, Ufe::Vector3d>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3d>::set(const Ufe::Vector3d& value) { setUsdAttributeVectorFromUfe<GfVec3d, Ufe::Vector3d>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <typename T> T TypedUsdAttribute<T>::get() const { if (!hasValue()) return T(); PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(Ufe::Attribute::sceneItem())) && vt.IsHolding<T>()) { return vt.UncheckedGet<T>(); } return T(); } template <typename T> void TypedUsdAttribute<T>::set(const T& value) { setUsdAttr<T>(fUsdAttr, value); } //------------------------------------------------------------------------------ // UsdAttributeBool: //------------------------------------------------------------------------------ /*static*/ UsdAttributeBool::Ptr UsdAttributeBool::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeBool>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeInt: //------------------------------------------------------------------------------ /*static*/ UsdAttributeInt::Ptr UsdAttributeInt::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeInt>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeFloat: //------------------------------------------------------------------------------ /*static*/ UsdAttributeFloat::Ptr UsdAttributeFloat::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeFloat>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeDouble: //------------------------------------------------------------------------------ /*static*/ UsdAttributeDouble::Ptr UsdAttributeDouble::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeDouble>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeString: //------------------------------------------------------------------------------ /*static*/ UsdAttributeString::Ptr UsdAttributeString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeString>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeColorFloat3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeColorFloat3::Ptr UsdAttributeColorFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeColorFloat3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeInt3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeInt3::Ptr UsdAttributeInt3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeInt3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeFloat3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeFloat3::Ptr UsdAttributeFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeFloat3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeDouble3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeDouble3::Ptr UsdAttributeDouble3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeDouble3>(item, usdAttr); return attr; } #if 0 // Note: if we were to implement generic attribute setting (via string) this // would be the way it could be done. bool UsdAttribute::setValue(const std::string& value) { // Put the input string into a VtValue so we can cast it to the proper type. PXR_NS::VtValue val(value.c_str()); // Attempt to cast the value to what we want. Get a default value for this // attribute's type name. PXR_NS::VtValue defVal = fUsdAttr.GetTypeName().GetDefaultValue(); // Attempt to cast the given string to the default value's type. // If casting fails, attempt to continue with the given value. PXR_NS::VtValue cast = PXR_NS::VtValue::CastToTypeOf(val, defVal); if (!cast.IsEmpty()) cast.Swap(val); return setUsdAttr<PXR_NS::VtValue>(fUsdAttr, val); } #endif } // namespace ufe } // namespace MAYAUSD_NS_DEF
; A086801: a(n) = prime(n) - 3. ; -1,0,2,4,8,10,14,16,20,26,28,34,38,40,44,50,56,58,64,68,70,76,80,86,94,98,100,104,106,110,124,128,134,136,146,148,154,160,164,170,176,178,188,190,194,196,208,220,224,226,230,236,238,248,254,260,266,268,274,278 cal $0,40 ; The prime numbers. sub $0,3 mov $1,$0
global long_mode_start section .text bits 64 long_mode_start: mov ax, 0 mov ss, ax mov ds, ax mov es, ax mov fs, ax mov gs, ax extern rust_main call rust_main ; print `OKAY` to screen mov rax, 0x2f592f412f4b2f4f mov qword [0xb8000], rax hlt
;------------------------------------------------------------------------- ; Read/write driver for serial eeprom memory for micro8085_cilb ; Functions below assumes support for INTEL 8085 "undocumented" opcodes SECTION code_clib EXTERN eepgsz EXTERN sprxbf EXTERN spirx EXTERN sptxbf EXTERN spitx EXTERN puartd EXTERN puartc EXTERN uenabl EXTERN udtr EXTERN CPU_CLK_kHz PUBLIC _ee_mem_rd PUBLIC _ee_mem_wr ;------------------------------------------------------------------------- ; SERIAL EEPROM COMMANDS eewren equ 6H eerdsr equ 5H eewrdi equ 4H eerdda equ 3H eewrda equ 2H eewrsr equ 1H eewipb equ 1H ;------------------------------------------------------------------------- ; SERIAL EEPROM READ AND WRITE ;------------------------------------------------------------------------- ; extern bool ee_mem_rd(uint8 *pData, uint16 Address, uint16 Length); ;------------------------------------------------------------------------- _ee_mem_rd: call pollwip ;wait for write in progress to ld a,h ;finish before next access or l ;test for ok ret z ;otherwise return false ld de,sp+2 ;get arguments from stack ld hl,(de) ;last pushed is length ld a,h ;test for or l ;zero length jp z,eerd1 ;if so skip and return push hl ;save length inc de ;move to next inc de ;argument position ld hl,(de) ;which is address push hl ;save that too inc de ;move to first inc de ;argument position ld hl,(de) ;which is dataptr ex (sp),hl ;dptr to stack addr to hl ld b,h ;save addr ld c,l ;to bc call ee_cs_en ;SELECT EEPROM ld a,eerdda ;OPCODE READ DATA call spitx ;TRANSMIT OPCODE ld a,b ;GET ADDRESS HIGH BYTE call spitx ;TRANSMIT ld a,c ;GET ADDRESS LOW BYTE call spitx ;TRANSMIT pop hl ;get back dataptr pop bc ;get back length call sprxbf ;let spi in function finish call ee_cs_dis ;deselect eeprom chip eerd1: ld hl,1 ;return true ret ;------------------------------------------------------------------------- ; extern bool ee_mem_wr(uint8 *pData, uint16 Address, uint16 Length); ;------------------------------------------------------------------------- _ee_mem_wr: ld de,sp+2 ;get arguments from stack ld hl,(de) ;last pushed is length push hl ;save len on stack inc de ;move to next inc de ;argument position ld hl,(de) ;which is address push hl ;save it on stack inc de ;move to first inc de ;argument position ld hl,(de) ;which is dataptr ex (sp),hl ;dptr to stack addr to hl ex de,hl ;addr to de scrap hl ld a,e ;addr lsb to a and a,eepgsz-1 ;equals addr % pgsize ld b,0 ;copy intermediate ld c,a ;result to bc ld hl,eepgsz ;pglen = pgsize - (addr % pgsize) dsub ;hl now holds len within page ld b,h ;copy result ld c,l ;to bc which is size of jp eewr2 ;first chunk to page boundary eewr1: ld bc,eepgsz ;next chunk assume page size eewr2: pop hl ;get dptr at top of stack ex (sp),hl ;swap for length ld a,h ;test for zero or l ;remaining length jp z,eewr4 ;if so clean up and return call cphlbc ;compare tot - page jp nc,eewr3 ;jmp if tot >= page ld b,h ;else remaining is less than ld c,l ;full page so put len in bc eewr3: dsub ;sub chunk len from tot ex (sp),hl ;len to stack dptr to hl push hl ;correct order dptr on top push bc push de call pollwip ;let write in progress finish pop de pop bc ld a,h ;test ok result of or l ;write in progress jp z,eewr5 ;otherwise return false pop hl ;get dataptr call ee_write_pg ;execute write push hl ;save dataptr jp eewr1 ;continue eewr4: pop hl ;pop off working value ld hl,1 ;return true when ok ret eewr5: pop bc ;pop off twice pop bc ;return false (hl already zero) ret ;------------------------------------------------------------------------- ; compare hl - bc ; no carry if hl >= bc ; carry if hl < bc cphlbc: ld a,h ;compare hl - bc cp b ;and return ret nz ;correct c ld a,l ;and z cp c ;flags ret ;------------------------------------------------------------------------- ; Local arguments: Mem dataptr [HL], EEPROM addr [DE], length [BC] ; Returning Mem dptr and address incremented for next access, length zero ;------------------------------------------------------------------------- ee_write_pg: push hl ;save dptr push bc ;save length ld b,d ;copy address ld c,e ;to bc call ee_cs_en ;SELECT EEPROM ld a,eewren ;OPCODE WRITE ENABLE call spitx ;TRANSMIT IT call ee_cs_dis ;DESELECT call ee_cs_en ;SELECT AGAIN ld a,eewrda ;OPCODE WRITE DATA call spitx ;TRANSMIT IT ld a,b ;GET ADDRESS HIGH BYTE call spitx ;TRANSMIT ld a,c ;GET ADDRESS LOW BYTE call spitx ;TRANSMIT pop hl ;get back length ld d,h ;copy length ld e,l ;to de temporary add hl,bc ;add addr (bc) and len ex (sp),hl ;new addr to stack dptr to hl ld b,d ;copy length ld c,e ;to bc call sptxbf ;let spi out function finish call ee_cs_dis ;deselect eeprom chip pop de ;get back new address ret ;------------------------------------------------------------------------- ; datasheet says max write time for chip is 5 ms so poll and test for 10 ms ; one loop with spi_in + spi_out takes about 280us add 140us and do 25 loops ;------------------------------------------------------------------------- pollwip:ld b,25 ;POLL WRITE IN PROGRESS pollw1: call ee_cs_en ;SELECT EEPROM ld a,eerdsr ;OPCODE READ STATUS call spitx ;TRANSMIT OPCODE call spirx ;READ STATUS ld c,a ;TMP SAVE STATUS call ee_cs_dis ;DESELECT ld a,c ;RESTORE TMP SAVED ld hl,1 ;IF OK RETURN TRUE and eewipb ;MASK THE BIT ret z ;ZERO MEANS READY call delay140 ;ELSE ADD SOME DELAY dec b ;AND COUNT LOOPS jp nz,pollw1 ;MORE LOOPS TRY AGAIN ld hl,0 ;ELSE RETURN HL=0 FALSE ret ;------------------------------------------------------------------------- ee_cs_en: ld a,uenabl+udtr ;eeprom chip select on DTR line out (puartc),a ;uart control reg ret ;------------------------------------------------------------------------- ee_cs_dis: ld a,uenabl ;disable RTS and DTR lines out (puartc),a ;uart control reg ret ;------------------------------------------------------------------------- delay140: ;(2/XTAL)*n*(4+10)=140us -> n=XTAL_kHz/200 ld h,CPU_CLK_kHz/200 delay2: dec h ;4 clock cycles jp nz,delay2 ;10 clock cycles ret ;returning zero in h
.section __DATA,__data # __DATA er segment, __data er seksjon (ref Mach-O format) .section __TEXT,__text # __TEXT er segment, __text er seksjon (fef Mach-0 format) # din kode
; void SMS_VRAMmemcpy_brief(unsigned int dst,void *src,unsigned char size) SECTION code_clib SECTION code_SMSlib PUBLIC SMS_VRAMmemcpy_brief EXTERN asm_SMSlib_VRAMmemcpy_brief SMS_VRAMmemcpy_brief: pop af pop bc pop de pop hl push hl push de push bc push af ld b,c jp asm_SMSlib_VRAMmemcpy_brief
JMP END LABEL START LD R0, 1 LD R1, 2 ADD R0, R1 LD R2, 5 LD R3, 3 SUB R2, R3 LD R0, 3 LD R1, 5 MUL R0, R1 LD R2, 10 LD R3, 2 DIV R2, R3 LABEL END JMP START
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/redundancy-elimination.h" #include "src/compiler/node-properties.h" #include "src/compiler/simplified-operator.h" namespace v8 { namespace internal { namespace compiler { RedundancyElimination::RedundancyElimination(Editor* editor, Zone* zone) : AdvancedReducer(editor), node_checks_(zone), zone_(zone) {} RedundancyElimination::~RedundancyElimination() = default; Reduction RedundancyElimination::Reduce(Node* node) { if (node_checks_.Get(node)) return NoChange(); switch (node->opcode()) { case IrOpcode::kCheckBounds: case IrOpcode::kCheckEqualsInternalizedString: case IrOpcode::kCheckEqualsSymbol: case IrOpcode::kCheckFloat64Hole: case IrOpcode::kCheckHeapObject: case IrOpcode::kCheckIf: case IrOpcode::kCheckInternalizedString: case IrOpcode::kCheckNotTaggedHole: case IrOpcode::kCheckNumber: case IrOpcode::kCheckReceiver: case IrOpcode::kCheckReceiverOrNullOrUndefined: case IrOpcode::kCheckSmi: case IrOpcode::kCheckString: case IrOpcode::kCheckSymbol: #define SIMPLIFIED_CHECKED_OP(Opcode) case IrOpcode::k##Opcode: SIMPLIFIED_CHECKED_OP_LIST(SIMPLIFIED_CHECKED_OP) #undef SIMPLIFIED_CHECKED_OP return ReduceCheckNode(node); case IrOpcode::kSpeculativeNumberEqual: case IrOpcode::kSpeculativeNumberLessThan: case IrOpcode::kSpeculativeNumberLessThanOrEqual: return ReduceSpeculativeNumberComparison(node); case IrOpcode::kSpeculativeNumberAdd: case IrOpcode::kSpeculativeNumberSubtract: case IrOpcode::kSpeculativeSafeIntegerAdd: case IrOpcode::kSpeculativeSafeIntegerSubtract: case IrOpcode::kSpeculativeToNumber: return ReduceSpeculativeNumberOperation(node); case IrOpcode::kEffectPhi: return ReduceEffectPhi(node); case IrOpcode::kDead: break; case IrOpcode::kStart: return ReduceStart(node); default: return ReduceOtherNode(node); } return NoChange(); } // static RedundancyElimination::EffectPathChecks* RedundancyElimination::EffectPathChecks::Copy(Zone* zone, EffectPathChecks const* checks) { return new (zone->New(sizeof(EffectPathChecks))) EffectPathChecks(*checks); } // static RedundancyElimination::EffectPathChecks const* RedundancyElimination::EffectPathChecks::Empty(Zone* zone) { return new (zone->New(sizeof(EffectPathChecks))) EffectPathChecks(nullptr, 0); } bool RedundancyElimination::EffectPathChecks::Equals( EffectPathChecks const* that) const { if (this->size_ != that->size_) return false; Check* this_head = this->head_; Check* that_head = that->head_; while (this_head != that_head) { if (this_head->node != that_head->node) return false; this_head = this_head->next; that_head = that_head->next; } return true; } void RedundancyElimination::EffectPathChecks::Merge( EffectPathChecks const* that) { // Change the current check list to a longest common tail of this check // list and the other list. // First, we throw away the prefix of the longer list, so that // we have lists of the same length. Check* that_head = that->head_; size_t that_size = that->size_; while (that_size > size_) { that_head = that_head->next; that_size--; } while (size_ > that_size) { head_ = head_->next; size_--; } // Then we go through both lists in lock-step until we find // the common tail. while (head_ != that_head) { DCHECK_LT(0u, size_); DCHECK_NOT_NULL(head_); size_--; head_ = head_->next; that_head = that_head->next; } } RedundancyElimination::EffectPathChecks const* RedundancyElimination::EffectPathChecks::AddCheck(Zone* zone, Node* node) const { Check* head = new (zone->New(sizeof(Check))) Check(node, head_); return new (zone->New(sizeof(EffectPathChecks))) EffectPathChecks(head, size_ + 1); } namespace { // Does check {a} subsume check {b}? bool CheckSubsumes(Node const* a, Node const* b) { if (a->op() != b->op()) { if (a->opcode() == IrOpcode::kCheckInternalizedString && b->opcode() == IrOpcode::kCheckString) { // CheckInternalizedString(node) implies CheckString(node) } else if (a->opcode() == IrOpcode::kCheckSmi && b->opcode() == IrOpcode::kCheckNumber) { // CheckSmi(node) implies CheckNumber(node) } else if (a->opcode() == IrOpcode::kCheckedTaggedSignedToInt32 && b->opcode() == IrOpcode::kCheckedTaggedToInt32) { // CheckedTaggedSignedToInt32(node) implies CheckedTaggedToInt32(node) } else if (a->opcode() == IrOpcode::kCheckReceiver && b->opcode() == IrOpcode::kCheckReceiverOrNullOrUndefined) { // CheckReceiver(node) implies CheckReceiverOrNullOrUndefined(node) } else if (a->opcode() != b->opcode()) { return false; } else { switch (a->opcode()) { case IrOpcode::kCheckBounds: case IrOpcode::kCheckSmi: case IrOpcode::kCheckString: case IrOpcode::kCheckNumber: break; case IrOpcode::kCheckedInt32ToTaggedSigned: case IrOpcode::kCheckedInt64ToInt32: case IrOpcode::kCheckedInt64ToTaggedSigned: case IrOpcode::kCheckedTaggedSignedToInt32: case IrOpcode::kCheckedTaggedToTaggedPointer: case IrOpcode::kCheckedTaggedToTaggedSigned: case IrOpcode::kCheckedCompressedToTaggedPointer: case IrOpcode::kCheckedCompressedToTaggedSigned: case IrOpcode::kCheckedTaggedToCompressedPointer: case IrOpcode::kCheckedTaggedToCompressedSigned: case IrOpcode::kCheckedUint32Bounds: case IrOpcode::kCheckedUint32ToInt32: case IrOpcode::kCheckedUint32ToTaggedSigned: case IrOpcode::kCheckedUint64Bounds: case IrOpcode::kCheckedUint64ToInt32: case IrOpcode::kCheckedUint64ToTaggedSigned: break; case IrOpcode::kCheckedFloat64ToInt32: case IrOpcode::kCheckedFloat64ToInt64: case IrOpcode::kCheckedTaggedToInt32: case IrOpcode::kCheckedTaggedToInt64: { const CheckMinusZeroParameters& ap = CheckMinusZeroParametersOf(a->op()); const CheckMinusZeroParameters& bp = CheckMinusZeroParametersOf(b->op()); if (ap.mode() != bp.mode()) { return false; } break; } case IrOpcode::kCheckedTaggedToFloat64: case IrOpcode::kCheckedTruncateTaggedToWord32: { CheckTaggedInputParameters const& ap = CheckTaggedInputParametersOf(a->op()); CheckTaggedInputParameters const& bp = CheckTaggedInputParametersOf(b->op()); // {a} subsumes {b} if the modes are either the same, or {a} checks // for Number, in which case {b} will be subsumed no matter what. if (ap.mode() != bp.mode() && ap.mode() != CheckTaggedInputMode::kNumber) { return false; } break; } default: DCHECK(!IsCheckedWithFeedback(a->op())); return false; } } } for (int i = a->op()->ValueInputCount(); --i >= 0;) { if (a->InputAt(i) != b->InputAt(i)) return false; } return true; } bool TypeSubsumes(Node* node, Node* replacement) { if (!NodeProperties::IsTyped(node) || !NodeProperties::IsTyped(replacement)) { // If either node is untyped, we are running during an untyped optimization // phase, and replacement is OK. return true; } Type node_type = NodeProperties::GetType(node); Type replacement_type = NodeProperties::GetType(replacement); return replacement_type.Is(node_type); } } // namespace Node* RedundancyElimination::EffectPathChecks::LookupCheck(Node* node) const { for (Check const* check = head_; check != nullptr; check = check->next) { if (CheckSubsumes(check->node, node) && TypeSubsumes(node, check->node)) { DCHECK(!check->node->IsDead()); return check->node; } } return nullptr; } Node* RedundancyElimination::EffectPathChecks::LookupBoundsCheckFor( Node* node) const { for (Check const* check = head_; check != nullptr; check = check->next) { if (check->node->opcode() == IrOpcode::kCheckBounds && check->node->InputAt(0) == node) { return check->node; } } return nullptr; } RedundancyElimination::EffectPathChecks const* RedundancyElimination::PathChecksForEffectNodes::Get(Node* node) const { size_t const id = node->id(); if (id < info_for_node_.size()) return info_for_node_[id]; return nullptr; } void RedundancyElimination::PathChecksForEffectNodes::Set( Node* node, EffectPathChecks const* checks) { size_t const id = node->id(); if (id >= info_for_node_.size()) info_for_node_.resize(id + 1, nullptr); info_for_node_[id] = checks; } Reduction RedundancyElimination::ReduceCheckNode(Node* node) { Node* const effect = NodeProperties::GetEffectInput(node); EffectPathChecks const* checks = node_checks_.Get(effect); // If we do not know anything about the predecessor, do not propagate just yet // because we will have to recompute anyway once we compute the predecessor. if (checks == nullptr) return NoChange(); // See if we have another check that dominates us. if (Node* check = checks->LookupCheck(node)) { ReplaceWithValue(node, check); return Replace(check); } // Learn from this check. return UpdateChecks(node, checks->AddCheck(zone(), node)); } Reduction RedundancyElimination::ReduceEffectPhi(Node* node) { Node* const control = NodeProperties::GetControlInput(node); if (control->opcode() == IrOpcode::kLoop) { // Here we rely on having only reducible loops: // The loop entry edge always dominates the header, so we can just use // the information from the loop entry edge. return TakeChecksFromFirstEffect(node); } DCHECK_EQ(IrOpcode::kMerge, control->opcode()); // Shortcut for the case when we do not know anything about some input. int const input_count = node->op()->EffectInputCount(); for (int i = 0; i < input_count; ++i) { Node* const effect = NodeProperties::GetEffectInput(node, i); if (node_checks_.Get(effect) == nullptr) return NoChange(); } // Make a copy of the first input's checks and merge with the checks // from other inputs. EffectPathChecks* checks = EffectPathChecks::Copy( zone(), node_checks_.Get(NodeProperties::GetEffectInput(node, 0))); for (int i = 1; i < input_count; ++i) { Node* const input = NodeProperties::GetEffectInput(node, i); checks->Merge(node_checks_.Get(input)); } return UpdateChecks(node, checks); } Reduction RedundancyElimination::ReduceSpeculativeNumberComparison(Node* node) { NumberOperationHint const hint = NumberOperationHintOf(node->op()); Node* const first = NodeProperties::GetValueInput(node, 0); Type const first_type = NodeProperties::GetType(first); Node* const second = NodeProperties::GetValueInput(node, 1); Type const second_type = NodeProperties::GetType(second); Node* const effect = NodeProperties::GetEffectInput(node); EffectPathChecks const* checks = node_checks_.Get(effect); // If we do not know anything about the predecessor, do not propagate just yet // because we will have to recompute anyway once we compute the predecessor. if (checks == nullptr) return NoChange(); // Avoid the potentially expensive lookups below if the {node} // has seen non-Smi inputs in the past, which is a clear signal // that the comparison is probably not performed on a value that // already passed an array bounds check. if (hint == NumberOperationHint::kSignedSmall) { // Don't bother trying to find a CheckBounds for the {first} input // if it's type is already in UnsignedSmall range, since the bounds // check is only going to narrow that range further, but the result // is not going to make the representation selection any better. if (!first_type.Is(Type::UnsignedSmall())) { if (Node* check = checks->LookupBoundsCheckFor(first)) { if (!first_type.Is(NodeProperties::GetType(check))) { // Replace the {first} input with the {check}. This is safe, // despite the fact that {check} can truncate -0 to 0, because // the regular Number comparisons in JavaScript also identify // 0 and -0 (unlike special comparisons as Object.is). NodeProperties::ReplaceValueInput(node, check, 0); Reduction const reduction = ReduceSpeculativeNumberComparison(node); return reduction.Changed() ? reduction : Changed(node); } } } // Don't bother trying to find a CheckBounds for the {second} input // if it's type is already in UnsignedSmall range, since the bounds // check is only going to narrow that range further, but the result // is not going to make the representation selection any better. if (!second_type.Is(Type::UnsignedSmall())) { if (Node* check = checks->LookupBoundsCheckFor(second)) { if (!second_type.Is(NodeProperties::GetType(check))) { // Replace the {second} input with the {check}. This is safe, // despite the fact that {check} can truncate -0 to 0, because // the regular Number comparisons in JavaScript also identify // 0 and -0 (unlike special comparisons as Object.is). NodeProperties::ReplaceValueInput(node, check, 1); Reduction const reduction = ReduceSpeculativeNumberComparison(node); return reduction.Changed() ? reduction : Changed(node); } } } } return UpdateChecks(node, checks); } Reduction RedundancyElimination::ReduceSpeculativeNumberOperation(Node* node) { DCHECK(node->opcode() == IrOpcode::kSpeculativeNumberAdd || node->opcode() == IrOpcode::kSpeculativeNumberSubtract || node->opcode() == IrOpcode::kSpeculativeSafeIntegerAdd || node->opcode() == IrOpcode::kSpeculativeSafeIntegerSubtract || node->opcode() == IrOpcode::kSpeculativeToNumber); DCHECK_EQ(1, node->op()->EffectInputCount()); DCHECK_EQ(1, node->op()->EffectOutputCount()); Node* const first = NodeProperties::GetValueInput(node, 0); Node* const effect = NodeProperties::GetEffectInput(node); EffectPathChecks const* checks = node_checks_.Get(effect); // If we do not know anything about the predecessor, do not propagate just yet // because we will have to recompute anyway once we compute the predecessor. if (checks == nullptr) return NoChange(); // Check if there's a CheckBounds operation on {first} // in the graph already, which we might be able to // reuse here to improve the representation selection // for the {node} later on. if (Node* check = checks->LookupBoundsCheckFor(first)) { // Only use the bounds {check} if its type is better // than the type of the {first} node, otherwise we // would end up replacing NumberConstant inputs with // CheckBounds operations, which is kind of pointless. if (!NodeProperties::GetType(first).Is(NodeProperties::GetType(check))) { NodeProperties::ReplaceValueInput(node, check, 0); } } return UpdateChecks(node, checks); } Reduction RedundancyElimination::ReduceStart(Node* node) { return UpdateChecks(node, EffectPathChecks::Empty(zone())); } Reduction RedundancyElimination::ReduceOtherNode(Node* node) { if (node->op()->EffectInputCount() == 1) { if (node->op()->EffectOutputCount() == 1) { return TakeChecksFromFirstEffect(node); } else { // Effect terminators should be handled specially. return NoChange(); } } DCHECK_EQ(0, node->op()->EffectInputCount()); DCHECK_EQ(0, node->op()->EffectOutputCount()); return NoChange(); } Reduction RedundancyElimination::TakeChecksFromFirstEffect(Node* node) { DCHECK_EQ(1, node->op()->EffectOutputCount()); Node* const effect = NodeProperties::GetEffectInput(node); EffectPathChecks const* checks = node_checks_.Get(effect); // If we do not know anything about the predecessor, do not propagate just yet // because we will have to recompute anyway once we compute the predecessor. if (checks == nullptr) return NoChange(); // We just propagate the information from the effect input (ideally, // we would only revisit effect uses if there is change). return UpdateChecks(node, checks); } Reduction RedundancyElimination::UpdateChecks(Node* node, EffectPathChecks const* checks) { EffectPathChecks const* original = node_checks_.Get(node); // Only signal that the {node} has Changed, if the information about {checks} // has changed wrt. the {original}. if (checks != original) { if (original == nullptr || !checks->Equals(original)) { node_checks_.Set(node, checks); return Changed(node); } } return NoChange(); } } // namespace compiler } // namespace internal } // namespace v8
.data zero: .float 0.0 .text main: la $t0, zero l.s $f0, 0($t0) div.s $f0, $f0, $f0 mov.s $f1, $f0 c.le.s 5, $f0, $f1 bc1t 5, branch li $a0, 0 li $v0, 1 syscall branch: li $a0, 1 li $v0, 1 syscall
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: spreadsheetColumn.asm AUTHOR: Gene Anderson, Aug 27, 1992 ROUTINES: Name Description ---- ----------- MSG_SPREADSHEET_SET_ROW_HEIGHT MSG_SPREADSHEET_CHANGE_ROW_HEIGHT MSG_SPREADSHEET_SET_COLUMN_WIDTH MSG_SPREADSHEET_CHANGE_COLUMN_WIDTH INT RecalcRowHeights Recalculate row heights and baseline for selected rows INT RecalcRowHeightsInRange Recalculate the row-heights for a range of rows INT CalcRowHeight Calculate the row height based on pointsizes in use INT FindMaxPointsize Find the maximum pointsize of a row INT GetColumnsFromParams Get columns to use from message parameters INT GetRowsFromParams Get rows to use from message parameters INT GetColumnBestFit Get the best fit for a column INT CellBestFit Calculate the column width needed for one cell REVISION HISTORY: Name Date Description ---- ---- ----------- Gene 8/27/92 Initial revision DESCRIPTION: Routines and method handlers for rows and columns. $Id: spreadsheetRowColumn.asm,v 1.1 97/04/07 11:13:18 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AttrCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetSetRowHeight %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the row height of the current selection CALLED BY: MSG_SPREADSHEET_SET_ROW_HEIGHT PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the method cx - row height (ROW_HEIGHT_AUTOMATIC or'd for automatic) dx - SPREADSHEET_ADDRESS_USE_SELECTION or row # RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: The general rule for the baseline KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/10/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetSetRowHeight method dynamic SpreadsheetClass, \ MSG_SPREADSHEET_SET_ROW_HEIGHT .enter call SpreadsheetMarkBusy mov si, di ;ds:si <- ptr to instance data call GetRowsFromParams ;(ax,cx) <- range of rows jc done ; ; For each row selected, set the height ; mov bx, dx andnf dx, not (ROW_HEIGHT_AUTOMATIC) ;dx <- height andnf bx, (ROW_HEIGHT_AUTOMATIC) ;bx <- flag push ax rowLoop: call RowSetHeight inc ax ;ax <- next row cmp ax, cx ;at end? jbe rowLoop ;branch while more rows pop ax ; ; Recalculate the row heights ; call RecalcRowHeightsInRange ; ; Recalcuate the document size for the view, update the UI, ; and redraw ; mov ax, mask SNF_CELL_WIDTH_HEIGHT call UpdateDocUIRedrawAll done: call SpreadsheetMarkNotBusy .leave ret SpreadsheetSetRowHeight endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetChangeRowHeight %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Change height of a row CALLED BY: MSG_SPREADSHEET_CHANGE_ROW_HEIGHT PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the message cx - change in row height dx - SPREADSHEET_ADDRESS_USE_SELECTION or row # RETURN: DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 7/29/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetChangeRowHeight method dynamic SpreadsheetClass, \ MSG_SPREADSHEET_CHANGE_ROW_HEIGHT call SpreadsheetMarkBusy mov si, di ;ds:si <- ptr to spreadsheet mov bp, cx ;bp <- change in height call GetRowsFromParams ;(ax,cx) <- range of rows jc done ; ; For each row, change the height ; clr bx ;bx <- no baseline push ax rowLoop: call RowGetHeightFar ;dx <- current height add dx, bp ;dx <- new height call RowSetHeight inc ax ;ax <- next row cmp ax, cx ;at end? jbe rowLoop pop ax ; ; Recalculate the row heights ; call RecalcRowHeightsInRange ; ; Recalculate the document size for the view, update the UI, ; and redraw ; mov ax, mask SNF_CELL_WIDTH_HEIGHT call UpdateDocUIRedrawAll done: call SpreadsheetMarkNotBusy ret SpreadsheetChangeRowHeight endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RecalcRowHeights %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Recalculate row heights and baseline for selected rows CALLED BY: SpreadsheetSetRowHeight(), SpreadsheetSetPointsize() PASS: ds:si - ptr to Spreadsheet instance RETURN: none DESTROYED: ax, bx, cx, dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RecalcRowHeightsFar proc far class SpreadsheetClass .enter EC < call ECCheckInstancePtr ;> ; ; For each selected row, see if we should recalculate ; the height based on the pointsize change. ; mov ax, ds:[si].SSI_selected.CR_start.CR_row mov cx, ds:[si].SSI_selected.CR_end.CR_row call RecalcRowHeightsInRange .leave ret RecalcRowHeightsFar endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RecalcRowHeightsInRange %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Recalculate the row-heights for a range of rows. CALLED BY: RecalcRowHeights, SpreadsheetInsertSpace PASS: ds:si = Spreadsheet instance ax = Top row of range cx = Bottom row of range RETURN: nothing DESTROYED: bx, cx, dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 7/12/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RecalcRowHeightsInRange proc far uses di .enter EC < call ECCheckInstancePtr ;> sub cx, ax inc cx ;cx <- # of rows to set rowLoop: call RowGetBaseline ;bx <- baseline and flag test dx, ROW_HEIGHT_AUTOMATIC ;automatic height? jz manualHeight ;branch if manual call CalcRowHeight ;calculate row height ornf bx, ROW_HEIGHT_AUTOMATIC ;bx <- set as automatic setHeight: call RowSetHeight inc ax ;ax <- next row loop rowLoop .leave ret ; ; The row height is marked as manual. We still ; need to calculate the baseline, but the height ; remains unchanged. ; manualHeight: push ax call RowGetHeightFar ;dx <- current row height push dx call CalcRowHeight ;bx <- baseline mov ax, dx ;ax <- calculated height pop dx ;dx <- current row height add bx, dx ;bx <- baseline = baseline sub bx, ax ; + (height - calculated) pop ax jns setHeight ;baseline above bottom ; of cell? clr bx ;if not, Sbaseline = 0 jmp setHeight RecalcRowHeightsInRange endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CalcRowHeight %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calculate the row height based on pointsizes in use CALLED BY: SpreadsheetSetRowHeight() PASS: ds:si - ptr to Spreadsheet instance data ax - row # RETURN: dx - new row height bx - new baseline offset DESTROYED: bx, dx, di PSEUDO CODE/STRATEGY: row_height = MAX(pointsize) * 1.25 baseline = MAX(pointsize) - 1 NOTE: in order to include pointsize in the optimizations used for setting attributes on an entire column, this routine will need to change a fair amount... KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/11/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CalcRowHeight proc near uses ax, cx, es class SpreadsheetClass locals local CellLocals .enter EC < call ECCheckInstancePtr ;> mov bx, ax mov cx, MIN_ROW mov dx, ds:[si].SSI_maxCol ;(ax,bx,cx,dx) <- range to enum mov ss:locals.CL_data1, cx ;pass data word #1 clr di ;di <- RangeEnumFlags mov ss:locals.CL_data2, di ;pass data word #2 mov ss:locals.CL_params.REP_callback.segment, SEGMENT_CS mov ss:locals.CL_params.REP_callback.offset, offset FindMaxPointsize call CallRangeEnum ;ax <- max pointsize * 8 ; ; See if all cells had data. If not, we need to take into account ; the default pointsize, as that is what empty cells have. ; cmp ss:locals.CL_data2, dx ;all cells have data? je noEmptyCells ;branch if all cells filled mov ax, DEFAULT_STYLE_TOKEN ;ax <- style to get mov bx, offset CA_pointsize ;bx <- CellAttrs field call StyleGetAttrByTokenFar ;ax <- pointsize cmp ax, ss:locals.CL_data1 ;larger than maximum? ja defaultIsMax ;branch if new maximum noEmptyCells: mov ax, ss:locals.CL_data1 ;ax <- (pointsize * 8) defaultIsMax: mov dx, ax ;dx <- (pointsize * 8) mov bx, ax shr bx, 1 shr bx, 1 ;bx <- (pointsize * 8) / 4 add dx, bx ;dx <- (pointsize * 8) * 1.25 dec ax ;ax <- pointsize - 1 mov bx, ax ;bx <- pointsize - 1 shr dx, 1 shr dx, 1 shr dx, 1 ;dx <- new row height shr bx, 1 shr bx, 1 shr bx, 1 ;bx <- new baseline .leave ret CalcRowHeight endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindMaxPointsize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Find the maximum pointsize of a row. CALLED BY: CalcRowHeight() via RangeEnum() PASS: (ax,cx) - current cell (r,c) bx - handle of file ss:bp - ptr to CellLocals variables CL_data1 - maximum pointsize CL_data2 - # of cells called back for *es:di - ptr to cell data, if any ds:si - ptr to Spreadsheet instance carry - set if cell has data RETURN: carry - set to abort enumeration CL_data1 - (new) maximum pointsize CL_data2 - # of cells, updated DESTROYED: dh PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/12/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindMaxPointsize proc far uses ax, bx, cx, dx, si, di, ds, es locals local CellLocals .enter inherit EC < ERROR_NC BAD_CALLBACK_FOR_EMPTY_CELL ;> EC < call ECCheckInstancePtr ;> mov di, es:[di] ;es:di <- ptr to cell mov ax, es:[di].CC_attrs ;ax <- style token segmov es, ss lea di, ss:locals.CL_cellAttrs ;es:di <- ptr to style buffer call StyleGetStyleByTokenFar mov ax, ss:locals.CL_cellAttrs.CA_pointsize cmp ax, ss:locals.CL_data1 ;larger pointsize? jbe notBigger mov ss:locals.CL_data1, ax ;store new maximum pointsize notBigger: clc ;carry <- don't abort .leave ret FindMaxPointsize endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetSetColumnWidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the column width for selected columns CALLED BY: MSG_SPREADSHEET_SET_COLUMN_WIDTH PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the method cx - column width COLUMN_WIDTH_BEST_FIT - OR'ed for best fit dx - SPREADSHEET_ADDRESS_USE_SELECTION or row # RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetSetColumnWidth method dynamic SpreadsheetClass, \ MSG_SPREADSHEET_SET_COLUMN_WIDTH .enter call SpreadsheetMarkBusy mov si, di ;ds:si <- ptr to instance call GetColumnsFromParams ;(cx,ax) <- columns jc done test dx, COLUMN_WIDTH_BEST_FIT jnz getBestFit RoundToByte dx ;dx <- round to byte multiple ; ; HACK: if the rounding the new column will give the current column ; width, send out bogus notification with the unrounded column width ; so that when we send out notification with the rounded column ; width, the GCN list mechanism won't ignore it because the new column ; width notification is the same as the current column width ; notification. We want the new column width notification to occur ; because the column width controller is still display the unrounded ; column width that the user just entered - brianc 10/11/94 ; dx = new rounded column width ; mov bx, dx ;bx = new rounded column width call ColumnGetWidthFar ;dx = current width xchg bx, dx ;dx = new rounded column width ;bx = current width cmp bx, dx ;same? jne columnLoop ;nope, notification will work call SS_SendNotificationBogusWidth ;else, send bogus notif first columnLoop: call ColumnSetWidth inc cx ;cx <- next column cmp cx, ax ;end of selection? jbe columnLoop ;branch while more columns ; ; Recalcuate the document size for the view, update the UI, ; and redraw ; doneColumns: mov ax, mask SNF_CELL_WIDTH_HEIGHT call UpdateDocUIRedrawAll done: call SpreadsheetMarkNotBusy .leave ret ; ; Find the width of all the strings in the column and set the ; width based on them. ; getBestFit: call GetColumnBestFit cmp dx, 0 ;no data? je noData ;branch if no data add dx, 7 ;dx <- always round up RoundToByte dx ;dx <- round to byte multiple cmp dx, SS_COLUMN_WIDTH_MAX ;width too large? jbe widthOK ;branch if OK mov dx, SS_COLUMN_WIDTH_MAX ;dx <- set to maximum width widthOK: call ColumnSetWidth inc cx ;cx <- next column cmp cx, ax ;end of selection? jbe getBestFit jmp doneColumns ; ; The column had no data -- set the width to the default ; noData: mov dx, COLUMN_WIDTH_DEFAULT jmp widthOK SpreadsheetSetColumnWidth endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetChangeColumnWidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Make the selected columns wider/narrower CALLED BY: MSG_SPREADSHEET_CHANGE_COLUMN_WIDTH PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the method cx - change in column widths dx - SPREADSHEET_ADDRESS_USE_SELECTION or column # RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetChangeColumnWidth method dynamic SpreadsheetClass, \ MSG_SPREADSHEET_CHANGE_COLUMN_WIDTH .enter call SpreadsheetMarkBusy mov bx, cx ;bx <- delta for widths mov si, di ;ds:si <- ptr to instance call GetColumnsFromParams ;(cx,ax) <- columns to use jc done columnLoop: ; ; bx = Amount to change the column width by. ; call ColumnGetWidthFar ;dx <- column width add dx, bx ;dx <- new column width ; ; Make sure that the column isn't too narrow/wide. ; jns notTooNarrow ;branch if not too negative clr dx ;new width notTooNarrow: cmp dx, SS_COLUMN_WIDTH_MAX ;check for too wide jbe notTooWide ;branch if not too wide mov dx, SS_COLUMN_WIDTH_MAX ;new width notTooWide: RoundToByte dx ;dx <- round to byte multiple ; ; dx = new column width. ; call ColumnSetWidth ;set new width inc cx ;cx <- next column cmp cx, ax ;end of selection? jbe columnLoop ;branch while more columns ; ; Recalcuate the document size for the view, update the UI, ; and redraw ; mov ax, mask SNF_CELL_WIDTH_HEIGHT call UpdateDocUIRedrawAll done: call SpreadsheetMarkNotBusy .leave ret SpreadsheetChangeColumnWidth endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetColumnsFromParams %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get columns to use from message parameters CALLED BY: UTILITY PASS: ds:si - ptr to Spreadsheet instance dx - SPREADSHEET_ADDRESS_USE_SELECTION or column # RETURN: dx - old cx cx - start column ax - end column carry SET if column range invalid DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 7/29/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetColumnsFromParams proc near class SpreadsheetClass uses bx .enter push cx ; ; Assume using the passed column ; mov cx, dx ;cx <- start column mov ax, dx ;ax <- end column cmp ax, SPREADSHEET_ADDRESS_USE_SELECTION jne done ; ; Use current selection ; mov cx, ds:[si].SSI_selected.CR_start.CR_column mov ax, ds:[si].SSI_selected.CR_end.CR_column done: pop dx ;dx <- old cx xchg ax, cx mov bx, offset SDO_rowCol.CR_column call CheckMinRowOrColumn xchg ax, cx .leave ret GetColumnsFromParams endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetRowsFromParams %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get rows to use from message parameters CALLED BY: UTILITY PASS: ds:si - ptr to Spreadsheet instance dx - SPREADSHEET_ADDRESS_USE_SELECTION or row # RETURN: dx - old cx ax - start row cx - end row carry SET if range invalid DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 7/29/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetRowsFromParams proc near class SpreadsheetClass uses bx .enter push cx ; ; Assume using the passed row ; mov ax, dx ;ax <- start row mov cx, dx ;cx <- end row cmp ax, SPREADSHEET_ADDRESS_USE_SELECTION jne done ; ; Use current selection ; mov ax, ds:[si].SSI_selected.CR_start.CR_row mov cx, ds:[si].SSI_selected.CR_end.CR_row done: pop dx ;dx <- old cx mov bx, offset SDO_rowCol.CR_row call CheckMinRowOrColumn .leave ret GetRowsFromParams endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CheckMinRowOrColumn %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Check the passed pair of rows or columns against the spreadsheet's minimum CALLED BY: GetRowsFromParams, GetColumnsFromParams PASS: (ax, cx) - min, max pair bx - offset to vardata to check ds:si - pointer to spreadsheet instance data RETURN: if range invalid: carry SET else: ax - fixed up if necessary DESTROYED: bx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 12/ 1/94 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CheckMinRowOrColumn proc near class SpreadsheetClass uses si .enter test ds:[si].SSI_flags, mask SF_NONZERO_DOC_ORIGIN jz checkZero push ax, bx ; offset to vardata field mov si, ds:[si].SSI_chunk mov ax, TEMP_SPREADSHEET_DOC_ORIGIN call ObjVarFindData pop ax, si jnc checkZero mov bx, ds:[bx][si] ; min row or column checkMin: cmp cx, bx stc jl done ; entire range is bad cmp ax, bx jg done ; ; Beginning of range needs to be moved up ; mov ax, bx done: .leave ret checkZero: clr bx jmp checkMin CheckMinRowOrColumn endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetColumnBestFit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the best fit for a column CALLED BY: SpreadsheetSetColumnWidth() PASS: ds:si - ptr to Spreadsheet instance cx - column # RETURN: dx - best column width DESTROYED: bx, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetColumnBestFit proc near uses ax class SpreadsheetClass locals local CellLocals .enter clr ax mov bx, ds:[si].SSI_maxRow mov dx, cx ;(ax,cx),(bx,dx) <- range call CreateGStateFar mov ss:locals.CL_gstate, di ;pass GState mov ss:locals.CL_params.REP_callback.segment, SEGMENT_CS mov ss:locals.CL_params.REP_callback.offset, offset CellBestFit clr ss:locals.CL_data1 ;<- maximum width so far clr di ;di <- RangeEnumFlags call CallRangeEnum ; ; Return the maximum we found ; mov dx, ss:locals.CL_data1 ;dx <- maximum width found call DestroyGStateFar .leave ret GetColumnBestFit endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CellBestFit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calculate the column width needed for one cell CALLED BY: GetColumnBestFit() via RangeEnum() PASS: ss:bp - ptr to CallRangeEnum() local variables ds:si - ptr to SpreadsheetInstance data (ax,cx) - cell coordinates (r,c) carry - set if cell has data *es:di - ptr to cell data, if any CL_data1 - maximum width so far RETURN: carry - set to abort enum DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SizeBadCellType proc near EC < ERROR ILLEGAL_CELL_TYPE > NEC < ret > SizeBadCellType endp cellSizeRoutines nptr \ SizeTextCell, ;CT_TEXT SizeConstantCell, ;CT_CONSTANT SizeFormulaCell, ;CT_FORMULA SizeBadCellType, ;CT_NAME SizeBadCellType, ;CT_CHART SizeBadCellType, ;CT_EMPTY SizeDisplayFormulaCell ;CT_DISPLAY_FORMULA CheckHack <(size cellSizeRoutines) eq CellType> CellBestFit proc far uses ax, bx, cx, dx, si, di, ds, es locals local CellLocals .enter inherit EC < ERROR_NC BAD_CALLBACK_FOR_EMPTY_CELL ;> mov bx, ss:locals.CL_gstate ;bx <- GState to draw with xchg bx, di ;*es:bx <- ptr to cell data ;di <- GState to use ; ; Set up the GState based on the current cell attributes ; mov bx, es:[bx] ;es:bx <- ptr to cell data mov dx, es:[bx].CC_attrs ;dx <- cell style attrs call SetCellGStateAttrsFar ;setup GState, locals correctly ; ; Get a pointer to the cell data and the type ; mov dx, bx ;es:dx <- ptr to cell data mov bl, es:[bx].CC_type cmp bl, CT_EMPTY ;no data? je done ;branch if empty clr bh ;bx <- cell type ; ; Get the data in text format ; call cs:cellSizeRoutines[bx] ;ds:si <- ptr to text ; ; Get the width of the text string, and see if it is a new largest value ; clr cx ;cx <- text is NULL terminated call GrTextWidth ;dx <- width add dx, (CELL_INSET)*2 cmp dx, ss:locals.CL_data1 ;largest so far? jbe done ;branch if not largest mov ss:locals.CL_data1, dx ;store new largest done: clc ;carry <- don't abort .leave ret CellBestFit endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SizeTextCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get text for a text cell for calculating size CALLED BY: CellBestFit() PASS: es:dx - ptr to cell data RETURN: ds:si - ptr text string DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SizeTextCell proc near .enter segmov ds, es mov si, dx ;ds:si <- ptr to cell data add si, (size CellText) ;ds:si <- ptr to string .leave ret SizeTextCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SizeConstantCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get text for a constant cell CALLED BY: CellBestFit() PASS: es:dx - ptr to cell data ds:si - ptr to Spreadsheet instance ss:bp - inherited CellLocals RETURN: ds:si - ptr to text string DESTROYED: ax, bx, cx, es PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SizeConstantCell proc near class SpreadsheetClass uses di locals local CellLocals .enter inherit mov bx, ds:[si].SSI_cellParams.CFP_file mov cx, ds:[si].SSI_formatArray segmov ds, es, ax mov si, dx add si, offset CC_current ;ds:si <- ptr to float number segmov es, ss, ax lea di, ss:locals.CL_buffer ;es:di <- ptr to the buffer mov ax, ss:locals.CL_cellAttrs.CA_format call FloatFormatNumber ;convert to ASCII segmov ds, ss mov si, di ;ds:si <- ptr to result string .leave ret SizeConstantCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SizeFormulaCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get text for a formula cell CALLED BY: CellBestFit() PASS: es:dx - ptr to cell data (ax,cx) - (r,c) of cell ds:si - ptr to Spreadsheet instance ss:bp - inherited CellLocals RETURN: ds:si - ptr to text string DESTROYED: ax, bx, cx, dx, es PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SizeFormulaCell proc near uses di, bp locals local CellLocals .enter inherit lea di, ss:locals.CL_buffer ;ss:di <- ptr to dest buffer mov bp, dx ;dx:bp <- ptr to cell data mov dx, es segmov es, ss ;es:di <- ptr to dest buffer call FormulaCellGetResult segmov ds, es, si mov si, di ;ds:si <- ptr to text .leave ret SizeFormulaCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SizeDisplayFormulaCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get text for a display formula cell CALLED BY: CellBestFit() PASS: es:dx - ptr to cell data (ax,cx) - (r,c) of cell ds:si - ptr to Spreadsheet instance ss:bp - inherited CellLocals RETURN: ds:si - ptr to text string DESTROYED: ax, bx, cx, dx, es PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SizeDisplayFormulaCell proc near uses di, bp locals local CellLocals .enter inherit lea di, ss:locals.CL_buffer ;ss:di <- ptr to dest buffer mov bp, dx ;dx:bp <- ptr to cell data mov dx, es segmov es, ss ;es:di <- ptr to dest buffer call FormulaDisplayCellGetResult segmov ds, es, si mov si, di ;ds:si <- ptr to text .leave ret SizeDisplayFormulaCell endp AttrCode ends
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/events/keycodes/keyboard_code_conversion_x.h" #define XK_3270 // for XK_3270_BackTab #include <X11/keysym.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/XF86keysym.h> #include "base/basictypes.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "ui/events/keycodes/dom4/keycode_converter.h" namespace ui { // Get an ui::KeyboardCode from an X keyevent KeyboardCode KeyboardCodeFromXKeyEvent(XEvent* xev) { // XLookupKeysym does not take into consideration the state of the lock/shift // etc. keys. So it is necessary to use XLookupString instead. KeySym keysym; XLookupString(&xev->xkey, NULL, 0, &keysym, NULL); KeyboardCode keycode = KeyboardCodeFromXKeysym(keysym); if (keycode == VKEY_UNKNOWN) { keysym = DefaultXKeysymFromHardwareKeycode(xev->xkey.keycode); keycode = KeyboardCodeFromXKeysym(keysym); } return keycode; } KeyboardCode KeyboardCodeFromXKeysym(unsigned int keysym) { // TODO(sad): Have |keysym| go through the X map list? switch (keysym) { case XK_BackSpace: return VKEY_BACK; case XK_Delete: case XK_KP_Delete: return VKEY_DELETE; case XK_Tab: case XK_KP_Tab: case XK_ISO_Left_Tab: case XK_3270_BackTab: return VKEY_TAB; case XK_Linefeed: case XK_Return: case XK_KP_Enter: case XK_ISO_Enter: return VKEY_RETURN; case XK_Clear: case XK_KP_Begin: // NumPad 5 without Num Lock, for crosbug.com/29169. return VKEY_CLEAR; case XK_KP_Space: case XK_space: return VKEY_SPACE; case XK_Home: case XK_KP_Home: return VKEY_HOME; case XK_End: case XK_KP_End: return VKEY_END; case XK_Page_Up: case XK_KP_Page_Up: // aka XK_KP_Prior return VKEY_PRIOR; case XK_Page_Down: case XK_KP_Page_Down: // aka XK_KP_Next return VKEY_NEXT; case XK_Left: case XK_KP_Left: return VKEY_LEFT; case XK_Right: case XK_KP_Right: return VKEY_RIGHT; case XK_Down: case XK_KP_Down: return VKEY_DOWN; case XK_Up: case XK_KP_Up: return VKEY_UP; case XK_Escape: return VKEY_ESCAPE; case XK_Kana_Lock: case XK_Kana_Shift: return VKEY_KANA; case XK_Hangul: return VKEY_HANGUL; case XK_Hangul_Hanja: return VKEY_HANJA; case XK_Kanji: return VKEY_KANJI; case XK_Henkan: return VKEY_CONVERT; case XK_Muhenkan: return VKEY_NONCONVERT; case XK_Zenkaku_Hankaku: return VKEY_DBE_DBCSCHAR; case XK_A: case XK_a: return VKEY_A; case XK_B: case XK_b: return VKEY_B; case XK_C: case XK_c: return VKEY_C; case XK_D: case XK_d: return VKEY_D; case XK_E: case XK_e: return VKEY_E; case XK_F: case XK_f: return VKEY_F; case XK_G: case XK_g: return VKEY_G; case XK_H: case XK_h: return VKEY_H; case XK_I: case XK_i: return VKEY_I; case XK_J: case XK_j: return VKEY_J; case XK_K: case XK_k: return VKEY_K; case XK_L: case XK_l: return VKEY_L; case XK_M: case XK_m: return VKEY_M; case XK_N: case XK_n: return VKEY_N; case XK_O: case XK_o: return VKEY_O; case XK_P: case XK_p: return VKEY_P; case XK_Q: case XK_q: return VKEY_Q; case XK_R: case XK_r: return VKEY_R; case XK_S: case XK_s: return VKEY_S; case XK_T: case XK_t: return VKEY_T; case XK_U: case XK_u: return VKEY_U; case XK_V: case XK_v: return VKEY_V; case XK_W: case XK_w: return VKEY_W; case XK_X: case XK_x: return VKEY_X; case XK_Y: case XK_y: return VKEY_Y; case XK_Z: case XK_z: return VKEY_Z; case XK_0: case XK_1: case XK_2: case XK_3: case XK_4: case XK_5: case XK_6: case XK_7: case XK_8: case XK_9: return static_cast<KeyboardCode>(VKEY_0 + (keysym - XK_0)); case XK_parenright: return VKEY_0; case XK_exclam: return VKEY_1; case XK_at: return VKEY_2; case XK_numbersign: return VKEY_3; case XK_dollar: return VKEY_4; case XK_percent: return VKEY_5; case XK_asciicircum: return VKEY_6; case XK_ampersand: return VKEY_7; case XK_asterisk: return VKEY_8; case XK_parenleft: return VKEY_9; case XK_KP_0: case XK_KP_1: case XK_KP_2: case XK_KP_3: case XK_KP_4: case XK_KP_5: case XK_KP_6: case XK_KP_7: case XK_KP_8: case XK_KP_9: return static_cast<KeyboardCode>(VKEY_NUMPAD0 + (keysym - XK_KP_0)); case XK_multiply: case XK_KP_Multiply: return VKEY_MULTIPLY; case XK_KP_Add: return VKEY_ADD; case XK_KP_Separator: return VKEY_SEPARATOR; case XK_KP_Subtract: return VKEY_SUBTRACT; case XK_KP_Decimal: return VKEY_DECIMAL; case XK_KP_Divide: return VKEY_DIVIDE; case XK_KP_Equal: case XK_equal: case XK_plus: return VKEY_OEM_PLUS; case XK_comma: case XK_less: return VKEY_OEM_COMMA; case XK_minus: case XK_underscore: return VKEY_OEM_MINUS; case XK_greater: case XK_period: return VKEY_OEM_PERIOD; case XK_colon: case XK_semicolon: return VKEY_OEM_1; case XK_question: case XK_slash: return VKEY_OEM_2; case XK_asciitilde: case XK_quoteleft: return VKEY_OEM_3; case XK_bracketleft: case XK_braceleft: return VKEY_OEM_4; case XK_backslash: case XK_bar: return VKEY_OEM_5; case XK_bracketright: case XK_braceright: return VKEY_OEM_6; case XK_quoteright: case XK_quotedbl: return VKEY_OEM_7; case XK_ISO_Level5_Shift: return VKEY_OEM_8; case XK_Shift_L: case XK_Shift_R: return VKEY_SHIFT; case XK_Control_L: case XK_Control_R: return VKEY_CONTROL; case XK_Meta_L: case XK_Meta_R: case XK_Alt_L: case XK_Alt_R: return VKEY_MENU; case XK_ISO_Level3_Shift: return VKEY_ALTGR; case XK_Multi_key: return VKEY_COMPOSE; case XK_Pause: return VKEY_PAUSE; case XK_Caps_Lock: return VKEY_CAPITAL; case XK_Num_Lock: return VKEY_NUMLOCK; case XK_Scroll_Lock: return VKEY_SCROLL; case XK_Select: return VKEY_SELECT; case XK_Print: return VKEY_PRINT; case XK_Execute: return VKEY_EXECUTE; case XK_Insert: case XK_KP_Insert: return VKEY_INSERT; case XK_Help: return VKEY_HELP; case XK_Super_L: return VKEY_LWIN; case XK_Super_R: return VKEY_RWIN; case XK_Menu: return VKEY_APPS; case XK_F1: case XK_F2: case XK_F3: case XK_F4: case XK_F5: case XK_F6: case XK_F7: case XK_F8: case XK_F9: case XK_F10: case XK_F11: case XK_F12: case XK_F13: case XK_F14: case XK_F15: case XK_F16: case XK_F17: case XK_F18: case XK_F19: case XK_F20: case XK_F21: case XK_F22: case XK_F23: case XK_F24: return static_cast<KeyboardCode>(VKEY_F1 + (keysym - XK_F1)); case XK_KP_F1: case XK_KP_F2: case XK_KP_F3: case XK_KP_F4: return static_cast<KeyboardCode>(VKEY_F1 + (keysym - XK_KP_F1)); case XK_guillemotleft: case XK_guillemotright: case XK_degree: // In the case of canadian multilingual keyboard layout, VKEY_OEM_102 is // assigned to ugrave key. case XK_ugrave: case XK_Ugrave: case XK_brokenbar: return VKEY_OEM_102; // international backslash key in 102 keyboard. // When evdev is in use, /usr/share/X11/xkb/symbols/inet maps F13-18 keys // to the special XF86XK symbols to support Microsoft Ergonomic keyboards: // https://bugs.freedesktop.org/show_bug.cgi?id=5783 // In Chrome, we map these X key symbols back to F13-18 since we don't have // VKEYs for these XF86XK symbols. case XF86XK_Tools: return VKEY_F13; case XF86XK_Launch5: return VKEY_F14; case XF86XK_Launch6: return VKEY_F15; case XF86XK_Launch7: return VKEY_F16; case XF86XK_Launch8: return VKEY_F17; case XF86XK_Launch9: return VKEY_F18; #if defined(TOOLKIT_GTK) case XF86XK_Refresh: case XF86XK_History: case XF86XK_OpenURL: case XF86XK_AddFavorite: case XF86XK_Go: case XF86XK_ZoomIn: case XF86XK_ZoomOut: // ui::AcceleratorGtk tries to convert the XF86XK_ keysyms on Chrome // startup. It's safe to return VKEY_UNKNOWN here since ui::AcceleratorGtk // also checks a Gdk keysym. http://crbug.com/109843 return VKEY_UNKNOWN; #endif // For supporting multimedia buttons on a USB keyboard. case XF86XK_Back: return VKEY_BROWSER_BACK; case XF86XK_Forward: return VKEY_BROWSER_FORWARD; case XF86XK_Reload: return VKEY_BROWSER_REFRESH; case XF86XK_Stop: return VKEY_BROWSER_STOP; case XF86XK_Search: return VKEY_BROWSER_SEARCH; case XF86XK_Favorites: return VKEY_BROWSER_FAVORITES; case XF86XK_HomePage: return VKEY_BROWSER_HOME; case XF86XK_AudioMute: return VKEY_VOLUME_MUTE; case XF86XK_AudioLowerVolume: return VKEY_VOLUME_DOWN; case XF86XK_AudioRaiseVolume: return VKEY_VOLUME_UP; case XF86XK_AudioNext: return VKEY_MEDIA_NEXT_TRACK; case XF86XK_AudioPrev: return VKEY_MEDIA_PREV_TRACK; case XF86XK_AudioStop: return VKEY_MEDIA_STOP; case XF86XK_AudioPlay: return VKEY_MEDIA_PLAY_PAUSE; case XF86XK_Mail: return VKEY_MEDIA_LAUNCH_MAIL; case XF86XK_LaunchA: // F3 on an Apple keyboard. return VKEY_MEDIA_LAUNCH_APP1; case XF86XK_LaunchB: // F4 on an Apple keyboard. case XF86XK_Calculator: return VKEY_MEDIA_LAUNCH_APP2; case XF86XK_WLAN: return VKEY_WLAN; case XF86XK_PowerOff: return VKEY_POWER; case XF86XK_MonBrightnessDown: return VKEY_BRIGHTNESS_DOWN; case XF86XK_MonBrightnessUp: return VKEY_BRIGHTNESS_UP; case XF86XK_KbdBrightnessDown: return VKEY_KBD_BRIGHTNESS_DOWN; case XF86XK_KbdBrightnessUp: return VKEY_KBD_BRIGHTNESS_UP; // TODO(sad): some keycodes are still missing. } DLOG(WARNING) << "Unknown keysym: " << base::StringPrintf("0x%x", keysym); return VKEY_UNKNOWN; } const char* CodeFromXEvent(XEvent* xev) { return KeycodeConverter::GetInstance()->NativeKeycodeToCode( xev->xkey.keycode); } uint16 GetCharacterFromXEvent(XEvent* xev) { char buf[6]; int bytes_written = XLookupString(&xev->xkey, buf, 6, NULL, NULL); DCHECK_LE(bytes_written, 6); base::string16 result; return (bytes_written > 0 && base::UTF8ToUTF16(buf, bytes_written, &result) && result.length() == 1) ? result[0] : 0; } unsigned int DefaultXKeysymFromHardwareKeycode(unsigned int hardware_code) { static const unsigned int kHardwareKeycodeMap[] = { 0, // 0x00: 0, // 0x01: 0, // 0x02: 0, // 0x03: 0, // 0x04: 0, // 0x05: 0, // 0x06: 0, // 0x07: 0, // 0x08: XK_Escape, // 0x09: XK_Escape XK_1, // 0x0A: XK_1 XK_2, // 0x0B: XK_2 XK_3, // 0x0C: XK_3 XK_4, // 0x0D: XK_4 XK_5, // 0x0E: XK_5 XK_6, // 0x0F: XK_6 XK_7, // 0x10: XK_7 XK_8, // 0x11: XK_8 XK_9, // 0x12: XK_9 XK_0, // 0x13: XK_0 XK_minus, // 0x14: XK_minus XK_equal, // 0x15: XK_equal XK_BackSpace, // 0x16: XK_BackSpace XK_Tab, // 0x17: XK_Tab XK_q, // 0x18: XK_q XK_w, // 0x19: XK_w XK_e, // 0x1A: XK_e XK_r, // 0x1B: XK_r XK_t, // 0x1C: XK_t XK_y, // 0x1D: XK_y XK_u, // 0x1E: XK_u XK_i, // 0x1F: XK_i XK_o, // 0x20: XK_o XK_p, // 0x21: XK_p XK_bracketleft, // 0x22: XK_bracketleft XK_bracketright, // 0x23: XK_bracketright XK_Return, // 0x24: XK_Return XK_Control_L, // 0x25: XK_Control_L XK_a, // 0x26: XK_a XK_s, // 0x27: XK_s XK_d, // 0x28: XK_d XK_f, // 0x29: XK_f XK_g, // 0x2A: XK_g XK_h, // 0x2B: XK_h XK_j, // 0x2C: XK_j XK_k, // 0x2D: XK_k XK_l, // 0x2E: XK_l XK_semicolon, // 0x2F: XK_semicolon XK_apostrophe, // 0x30: XK_apostrophe XK_grave, // 0x31: XK_grave XK_Shift_L, // 0x32: XK_Shift_L XK_backslash, // 0x33: XK_backslash XK_z, // 0x34: XK_z XK_x, // 0x35: XK_x XK_c, // 0x36: XK_c XK_v, // 0x37: XK_v XK_b, // 0x38: XK_b XK_n, // 0x39: XK_n XK_m, // 0x3A: XK_m XK_comma, // 0x3B: XK_comma XK_period, // 0x3C: XK_period XK_slash, // 0x3D: XK_slash XK_Shift_R, // 0x3E: XK_Shift_R 0, // 0x3F: XK_KP_Multiply XK_Alt_L, // 0x40: XK_Alt_L XK_space, // 0x41: XK_space XK_Caps_Lock, // 0x42: XK_Caps_Lock XK_F1, // 0x43: XK_F1 XK_F2, // 0x44: XK_F2 XK_F3, // 0x45: XK_F3 XK_F4, // 0x46: XK_F4 XK_F5, // 0x47: XK_F5 XK_F6, // 0x48: XK_F6 XK_F7, // 0x49: XK_F7 XK_F8, // 0x4A: XK_F8 XK_F9, // 0x4B: XK_F9 XK_F10, // 0x4C: XK_F10 XK_Num_Lock, // 0x4D: XK_Num_Lock XK_Scroll_Lock, // 0x4E: XK_Scroll_Lock }; if (hardware_code >= arraysize(kHardwareKeycodeMap)) { // Checks for arrow keys. switch (hardware_code) { case 0x6f: return XK_Up; case 0x71: return XK_Left; case 0x72: return XK_Right; case 0x74: return XK_Down; } return 0; } return kHardwareKeycodeMap[hardware_code]; } // TODO(jcampan): this method might be incomplete. int XKeysymForWindowsKeyCode(KeyboardCode keycode, bool shift) { switch (keycode) { case VKEY_NUMPAD0: return XK_KP_0; case VKEY_NUMPAD1: return XK_KP_1; case VKEY_NUMPAD2: return XK_KP_2; case VKEY_NUMPAD3: return XK_KP_3; case VKEY_NUMPAD4: return XK_KP_4; case VKEY_NUMPAD5: return XK_KP_5; case VKEY_NUMPAD6: return XK_KP_6; case VKEY_NUMPAD7: return XK_KP_7; case VKEY_NUMPAD8: return XK_KP_8; case VKEY_NUMPAD9: return XK_KP_9; case VKEY_MULTIPLY: return XK_KP_Multiply; case VKEY_ADD: return XK_KP_Add; case VKEY_SUBTRACT: return XK_KP_Subtract; case VKEY_DECIMAL: return XK_KP_Decimal; case VKEY_DIVIDE: return XK_KP_Divide; case VKEY_BACK: return XK_BackSpace; case VKEY_TAB: return shift ? XK_ISO_Left_Tab : XK_Tab; case VKEY_CLEAR: return XK_Clear; case VKEY_RETURN: return XK_Return; case VKEY_SHIFT: return XK_Shift_L; case VKEY_CONTROL: return XK_Control_L; case VKEY_MENU: return XK_Alt_L; case VKEY_APPS: return XK_Menu; case VKEY_ALTGR: return XK_ISO_Level3_Shift; case VKEY_COMPOSE: return XK_Multi_key; case VKEY_PAUSE: return XK_Pause; case VKEY_CAPITAL: return XK_Caps_Lock; case VKEY_KANA: return XK_Kana_Lock; case VKEY_HANJA: return XK_Hangul_Hanja; case VKEY_CONVERT: return XK_Henkan; case VKEY_NONCONVERT: return XK_Muhenkan; case VKEY_DBE_SBCSCHAR: return XK_Zenkaku_Hankaku; case VKEY_DBE_DBCSCHAR: return XK_Zenkaku_Hankaku; case VKEY_ESCAPE: return XK_Escape; case VKEY_SPACE: return XK_space; case VKEY_PRIOR: return XK_Page_Up; case VKEY_NEXT: return XK_Page_Down; case VKEY_END: return XK_End; case VKEY_HOME: return XK_Home; case VKEY_LEFT: return XK_Left; case VKEY_UP: return XK_Up; case VKEY_RIGHT: return XK_Right; case VKEY_DOWN: return XK_Down; case VKEY_SELECT: return XK_Select; case VKEY_PRINT: return XK_Print; case VKEY_EXECUTE: return XK_Execute; case VKEY_INSERT: return XK_Insert; case VKEY_DELETE: return XK_Delete; case VKEY_HELP: return XK_Help; case VKEY_0: return shift ? XK_parenright : XK_0; case VKEY_1: return shift ? XK_exclam : XK_1; case VKEY_2: return shift ? XK_at : XK_2; case VKEY_3: return shift ? XK_numbersign : XK_3; case VKEY_4: return shift ? XK_dollar : XK_4; case VKEY_5: return shift ? XK_percent : XK_5; case VKEY_6: return shift ? XK_asciicircum : XK_6; case VKEY_7: return shift ? XK_ampersand : XK_7; case VKEY_8: return shift ? XK_asterisk : XK_8; case VKEY_9: return shift ? XK_parenleft : XK_9; case VKEY_A: case VKEY_B: case VKEY_C: case VKEY_D: case VKEY_E: case VKEY_F: case VKEY_G: case VKEY_H: case VKEY_I: case VKEY_J: case VKEY_K: case VKEY_L: case VKEY_M: case VKEY_N: case VKEY_O: case VKEY_P: case VKEY_Q: case VKEY_R: case VKEY_S: case VKEY_T: case VKEY_U: case VKEY_V: case VKEY_W: case VKEY_X: case VKEY_Y: case VKEY_Z: return (shift ? XK_A : XK_a) + (keycode - VKEY_A); case VKEY_LWIN: return XK_Super_L; case VKEY_RWIN: return XK_Super_R; case VKEY_NUMLOCK: return XK_Num_Lock; case VKEY_SCROLL: return XK_Scroll_Lock; case VKEY_OEM_1: return shift ? XK_colon : XK_semicolon; case VKEY_OEM_PLUS: return shift ? XK_plus : XK_equal; case VKEY_OEM_COMMA: return shift ? XK_less : XK_comma; case VKEY_OEM_MINUS: return shift ? XK_underscore : XK_minus; case VKEY_OEM_PERIOD: return shift ? XK_greater : XK_period; case VKEY_OEM_2: return shift ? XK_question : XK_slash; case VKEY_OEM_3: return shift ? XK_asciitilde : XK_quoteleft; case VKEY_OEM_4: return shift ? XK_braceleft : XK_bracketleft; case VKEY_OEM_5: return shift ? XK_bar : XK_backslash; case VKEY_OEM_6: return shift ? XK_braceright : XK_bracketright; case VKEY_OEM_7: return shift ? XK_quotedbl : XK_quoteright; case VKEY_OEM_8: return XK_ISO_Level5_Shift; case VKEY_OEM_102: return shift ? XK_guillemotleft : XK_guillemotright; case VKEY_F1: case VKEY_F2: case VKEY_F3: case VKEY_F4: case VKEY_F5: case VKEY_F6: case VKEY_F7: case VKEY_F8: case VKEY_F9: case VKEY_F10: case VKEY_F11: case VKEY_F12: case VKEY_F13: case VKEY_F14: case VKEY_F15: case VKEY_F16: case VKEY_F17: case VKEY_F18: case VKEY_F19: case VKEY_F20: case VKEY_F21: case VKEY_F22: case VKEY_F23: case VKEY_F24: return XK_F1 + (keycode - VKEY_F1); case VKEY_BROWSER_BACK: return XF86XK_Back; case VKEY_BROWSER_FORWARD: return XF86XK_Forward; case VKEY_BROWSER_REFRESH: return XF86XK_Reload; case VKEY_BROWSER_STOP: return XF86XK_Stop; case VKEY_BROWSER_SEARCH: return XF86XK_Search; case VKEY_BROWSER_FAVORITES: return XF86XK_Favorites; case VKEY_BROWSER_HOME: return XF86XK_HomePage; case VKEY_VOLUME_MUTE: return XF86XK_AudioMute; case VKEY_VOLUME_DOWN: return XF86XK_AudioLowerVolume; case VKEY_VOLUME_UP: return XF86XK_AudioRaiseVolume; case VKEY_MEDIA_NEXT_TRACK: return XF86XK_AudioNext; case VKEY_MEDIA_PREV_TRACK: return XF86XK_AudioPrev; case VKEY_MEDIA_STOP: return XF86XK_AudioStop; case VKEY_MEDIA_PLAY_PAUSE: return XF86XK_AudioPlay; case VKEY_MEDIA_LAUNCH_MAIL: return XF86XK_Mail; case VKEY_MEDIA_LAUNCH_APP1: return XF86XK_LaunchA; case VKEY_MEDIA_LAUNCH_APP2: return XF86XK_LaunchB; case VKEY_WLAN: return XF86XK_WLAN; case VKEY_POWER: return XF86XK_PowerOff; case VKEY_BRIGHTNESS_DOWN: return XF86XK_MonBrightnessDown; case VKEY_BRIGHTNESS_UP: return XF86XK_MonBrightnessUp; case VKEY_KBD_BRIGHTNESS_DOWN: return XF86XK_KbdBrightnessDown; case VKEY_KBD_BRIGHTNESS_UP: return XF86XK_KbdBrightnessUp; default: LOG(WARNING) << "Unknown keycode:" << keycode; return 0; } } } // namespace ui
//------------------------------------------------------------------------------ // // Copyright (c) 2016, Linaro Limited. All rights reserved. // // This program and the accompanying materials // are licensed and made available under the terms and conditions of the BSD License // which accompanies this distribution. The full text of the license may be found at // http://opensource.org/licenses/bsd-license.php // // THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, // WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. // //------------------------------------------------------------------------------ INCLUDE AsmMacroExport.inc //------------------------------------------------------------------------------ RVCT_ASM_EXPORT ArmHasMpExtensions mrc p15,0,R0,c0,c0,5 // Get Multiprocessing extension (bit31) lsr R0, R0, #31 bx LR RVCT_ASM_EXPORT ArmReadIdMmfr0 mrc p15, 0, r0, c0, c1, 4 ; Read ID_MMFR0 Register bx lr END
#include "TrackInfoG4.hpp" #include "G4VProcess.hh" using namespace allpix; TrackInfoG4::TrackInfoG4(int custom_track_id, int parent_track_id, const G4Track* const aTrack) : custom_track_id_(custom_track_id), parent_track_id_(parent_track_id) { auto G4Process = aTrack->GetCreatorProcess(); origin_g4_process_type_ = (G4Process != nullptr) ? G4Process->GetProcessType() : -1; particle_id_ = aTrack->GetDynamicParticle()->GetPDGcode(); start_point_ = static_cast<ROOT::Math::XYZPoint>(aTrack->GetPosition()); origin_g4_vol_name_ = aTrack->GetVolume()->GetName(); origin_g4_process_name_ = (G4Process != nullptr) ? static_cast<std::string>(G4Process->GetProcessName()) : "none"; initial_kin_E_ = aTrack->GetKineticEnergy(); initial_tot_E_ = aTrack->GetTotalEnergy(); } void TrackInfoG4::finalizeInfo(const G4Track* const aTrack) { final_kin_E_ = aTrack->GetKineticEnergy(); final_tot_E_ = aTrack->GetTotalEnergy(); n_steps_ = aTrack->GetCurrentStepNumber(); end_point_ = static_cast<ROOT::Math::XYZPoint>(aTrack->GetPosition()); } int TrackInfoG4::getID() const { return custom_track_id_; } int TrackInfoG4::getParentID() const { return parent_track_id_; } ROOT::Math::XYZPoint TrackInfoG4::getStartPoint() const { return start_point_; } ROOT::Math::XYZPoint TrackInfoG4::getEndPoint() const { return end_point_; } int TrackInfoG4::getParticleID() const { return particle_id_; } int TrackInfoG4::getCreationProcessType() const { return origin_g4_process_type_; } int TrackInfoG4::getNumberOfSteps() const { return n_steps_; } double TrackInfoG4::getKineticEnergyInitial() const { return initial_kin_E_; } double TrackInfoG4::getTotalEnergyInitial() const { return initial_tot_E_; } double TrackInfoG4::getKineticEnergyFinal() const { return final_kin_E_; } double TrackInfoG4::getTotalEnergyFinal() const { return final_tot_E_; } std::string TrackInfoG4::getOriginatingVolumeName() const { return origin_g4_vol_name_; } std::string TrackInfoG4::getCreationProcessName() const { return origin_g4_process_name_; }
; A131912: Row sums of triangle A131911. ; 1,7,12,18,23,29,34,40,45,51,56,62,67,73,78,84,89,95,100,106,111,117,122,128,133,139,144,150,155,161,166,172,177,183,188,194,199,205,210,216,221,227,232,238,243,249,254,260,265,271,276,282,287,293,298 mul $0,11 add $0,3 div $0,2 mov $1,$0
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/s3/model/CreateBucketRequest.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::S3::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; CreateBucketRequest::CreateBucketRequest() : m_aCLHasBeenSet(false), m_bucketHasBeenSet(false), m_createBucketConfigurationHasBeenSet(false), m_grantFullControlHasBeenSet(false), m_grantReadHasBeenSet(false), m_grantReadACPHasBeenSet(false), m_grantWriteHasBeenSet(false), m_grantWriteACPHasBeenSet(false) { } Aws::String CreateBucketRequest::SerializePayload() const { XmlDocument payloadDoc = XmlDocument::CreateWithRootNode("CreateBucketConfiguration"); XmlNode parentNode = payloadDoc.GetRootElement(); parentNode.SetAttributeValue("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/"); m_createBucketConfiguration.AddToNode(parentNode); if(parentNode.HasChildren()) { return payloadDoc.ConvertToString(); } return ""; } Aws::Http::HeaderValueCollection CreateBucketRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; Aws::StringStream ss; if(m_aCLHasBeenSet) { headers.insert(Aws::Http::HeaderValuePair("x-amz-acl", BucketCannedACLMapper::GetNameForBucketCannedACL(m_aCL))); } if(m_grantFullControlHasBeenSet) { ss << m_grantFullControl; headers.insert(Aws::Http::HeaderValuePair("x-amz-grant-full-control", ss.str())); ss.str(""); } if(m_grantReadHasBeenSet) { ss << m_grantRead; headers.insert(Aws::Http::HeaderValuePair("x-amz-grant-read", ss.str())); ss.str(""); } if(m_grantReadACPHasBeenSet) { ss << m_grantReadACP; headers.insert(Aws::Http::HeaderValuePair("x-amz-grant-read-acp", ss.str())); ss.str(""); } if(m_grantWriteHasBeenSet) { ss << m_grantWrite; headers.insert(Aws::Http::HeaderValuePair("x-amz-grant-write", ss.str())); ss.str(""); } if(m_grantWriteACPHasBeenSet) { ss << m_grantWriteACP; headers.insert(Aws::Http::HeaderValuePair("x-amz-grant-write-acp", ss.str())); ss.str(""); } return headers; }
at (32) :index pad (2) :extra_length_bits pad (2) :length_value pad (2) :extra_distance_bits pad (2) :distance_value pad (2) at (42) set (requested_feedback_location, 0) at (64) :byte_copy_left pad (2) :byte_copy_right pad (2) :input_bit_order pad (2) :decompressed_pointer pad (2) :length_table pad (116) :distance_table pad (120) set (returned_parameters_location, 0) align (64) :initialize_memory set (udvm_memory_size, 8192) set (state_length, (udvm_memory_size - 64)) set (length_table_start, (((length_table - 4) + 65536) / 4)) set (length_table_mid, (length_table_start + 24)) set (distance_table_start, (distance_table / 4)) MULTILOAD (64, 122, circular_buffer, udvm_memory_size, 5, circular_buffer, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 1, 11, 1, 13, 1, 15, 1, 17, 2, 19, 2, 23, 2, 27, 2, 31, 3, 35, 3, 43, 3, 51, 3, 59, 4, 67, 4, 83, 4, 99, 4, 115, 5, 131, 5, 163, 5, 195, 5, 227, 0, 258, 0, 1, 0, 2, 0, 3, 0, 4, 1, 5, 1, 7, 2, 9, 2, 13, 3, 17, 3, 25, 4, 33, 4, 49, 5, 65, 5, 97, 6, 129, 6, 193, 7, 257, 7, 385, 8, 513, 8, 769, 9, 1025, 9, 1537, 10, 2049, 10, 3073, 11, 4097, 11, 6145, 12, 8193, 12, 12289, 13, 16385, 13, 24577) :decompress_sigcomp_message INPUT-BITS (3, extra_length_bits, !) :next_character INPUT-HUFFMAN (index, end_of_message, 4, 7, 0, 23, length_table_start, 1, 48, 191, 0, 0, 192, 199, length_table_mid, 1, 400, 511, 144) COMPARE ($index, length_table_start, literal, end_of_message, length_distance) :literal set (index_lsb, (index + 1)) OUTPUT (index_lsb, 1) COPY-LITERAL (index_lsb, 1, $decompressed_pointer) JUMP (next_character) :length_distance ; this is the length part MULTIPLY ($index, 4) COPY ($index, 4, extra_length_bits) INPUT-BITS ($extra_length_bits, extra_length_bits, !) ADD ($length_value, $extra_length_bits) ; this is the distance part INPUT-HUFFMAN (index, !, 1, 5, 0, 31, distance_table_start) MULTIPLY ($index, 4) COPY ($index, 4, extra_distance_bits) INPUT-BITS ($extra_distance_bits, extra_distance_bits, !) ADD ($distance_value, $extra_distance_bits) LOAD (index, $decompressed_pointer) COPY-OFFSET ($distance_value, $length_value, $decompressed_pointer) OUTPUT ($index, $length_value) JUMP (next_character) :end_of_message END-MESSAGE (requested_feedback_location, returned_parameters_location, state_length, 64, decompress_sigcomp_message, 6, 0) :circular_buffer
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/04/Mult.asm // Multiplies R0 and R1 and stores the result in R2. // (R0, R1, R2 refer to RAM[0], RAM[1], and RAM[2], respectively.) // Put your code here. @R2 M=0 @R0 D=M @END D;JEQ @R1 D=M @END D;JEQ @R1 D=M @R3 M=D (LOOP) @R0 D=M @R2 D=M+D @R2 M=D @R3 D=M M=D-1 D=M @LOOP D;JGT (END) @END 0;JMP
include mathhost.i CGROUP group code code segment dword 'CODE' assume cs:CGROUP,ds:CGROUP MATHLIB_2JUMP sinh _r_ml_sinh math_sinh code ends end
; Reverses the bits within a byte. ; ; Uses: a,b,c ; ; Entry: a a byte ; Exit: a a with its bits reversed. reverse_bits: ld c,8 ld b,a ; b is now the input value. xor a ; clear for output. __reverse_bits_loop: sla a srl b ; c >>> 1 jp nc,__reverse_bits_cont or a,1 __reverse_bits_cont: dec c ret z jr __reverse_bits_loop
\ LCD CONFIG -- cfg_2x16_lcd.asm ----------------------------------------------- \ \ Port B of the VIA is used for the Data pins on the LCD display. \ Three pins on Port A are used for signal pins on the LCD: \ - PA5 RS Register select \ - PA6 RW Read/Write \ - PA7 E Execute \ The other 5 pins - PA0-PA4 - are used for the LEDs. LED_ERR = 0 LED_BUSY = 1 LED_OK = 2 LED_FILE_ACT = 3 LED_DEBUG = 4 ; LCD PANEL LCD_LINES = 2 ; number of lines on display LCD_COLS = 16 ; number of chars per line LCD_LN_BUF_SZ = $28 ; 40 bytes - per line LCD_BUF_SZ = LCD_LINES * LCD_LN_BUF_SZ LCD_MOVE_SRC = 39 ; for 2-line display LCD_MOVE_DST = 79 ;LCD_MOVE_SRC = 79 ; for 4-line display ;LCD_MOVE_DST = 119 LCD_CLS = %00000001 ; Clear screen & reset display memory LCD_TYPE = %00111000 ; Set 8-bit mode; 2-line display; 5x8 font LCD_MODE = %00001100 ; Display on; cursor off; blink off LCD_CURS_HOME = %00000010 ; return cursor to home position LCD_CURS_L = %00010000 ; shifts cursor to the left LCD_CURS_R = %00010100 ; shifts cursor to the right LCD_EX = %10000000 ; Toggling this high enables execution of byte in register LCD_RW = %01000000 ; Read/Write bit: 0 = read; 1 = write LCD_RS = %00100000 ; Register select bit: 0 = instruction reg; 1 = data reg LCD_BUSY_FLAG = %10000000 LCD_SET_DDRAM = %10000000 ; to be ORed with a 7-bit value for the DDRAM address ; LEDs - LEDs 0-4 are on Port A, PA0-PA4 LED_MASK = %00011111 ; will be ORed with control bits for LCD on PORTA MACRO LED_ON led_num pha lda VIAA_PORTA ora #1 << led_num sta VIAA_PORTA pla ENDMACRO MACRO LED_TOGGLE led_num pha lda VIAA_PORTA eor #1 << led_num sta VIAA_PORTA pla ENDMACRO MACRO LED_OFF led_num pha lda #255 eor #(1 << led_num) and VIAA_PORTA sta VIAA_PORTA pla ENDMACRO MACRO LCD_SET_CTL ctl_bits ; set control bits for LCD lda VIAA_PORTA ; load the current state or PORT A and #LED_MASK ; clear the top three bits ora #ctl_bits ; set those bits. Lower 5 bits should be 0s sta VIAA_PORTA ; store result ENDMACRO
_zombie: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(void) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc push -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 04 sub $0x4,%esp if(fork() > 0) 11: e8 95 02 00 00 call 2ab <fork> 16: 85 c0 test %eax,%eax 18: 7e 0d jle 27 <main+0x27> sleep(5); // Let child exit before parent. 1a: 83 ec 0c sub $0xc,%esp 1d: 6a 05 push $0x5 1f: e8 1f 03 00 00 call 343 <sleep> 24: 83 c4 10 add $0x10,%esp exit(); 27: e8 87 02 00 00 call 2b3 <exit> 0000002c <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 2c: 55 push %ebp 2d: 89 e5 mov %esp,%ebp 2f: 57 push %edi 30: 53 push %ebx asm volatile("cld; rep stosb" : 31: 8b 4d 08 mov 0x8(%ebp),%ecx 34: 8b 55 10 mov 0x10(%ebp),%edx 37: 8b 45 0c mov 0xc(%ebp),%eax 3a: 89 cb mov %ecx,%ebx 3c: 89 df mov %ebx,%edi 3e: 89 d1 mov %edx,%ecx 40: fc cld 41: f3 aa rep stos %al,%es:(%edi) 43: 89 ca mov %ecx,%edx 45: 89 fb mov %edi,%ebx 47: 89 5d 08 mov %ebx,0x8(%ebp) 4a: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 4d: 90 nop 4e: 5b pop %ebx 4f: 5f pop %edi 50: 5d pop %ebp 51: c3 ret 00000052 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 52: 55 push %ebp 53: 89 e5 mov %esp,%ebp 55: 83 ec 10 sub $0x10,%esp char *os; os = s; 58: 8b 45 08 mov 0x8(%ebp),%eax 5b: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 5e: 90 nop 5f: 8b 55 0c mov 0xc(%ebp),%edx 62: 8d 42 01 lea 0x1(%edx),%eax 65: 89 45 0c mov %eax,0xc(%ebp) 68: 8b 45 08 mov 0x8(%ebp),%eax 6b: 8d 48 01 lea 0x1(%eax),%ecx 6e: 89 4d 08 mov %ecx,0x8(%ebp) 71: 0f b6 12 movzbl (%edx),%edx 74: 88 10 mov %dl,(%eax) 76: 0f b6 00 movzbl (%eax),%eax 79: 84 c0 test %al,%al 7b: 75 e2 jne 5f <strcpy+0xd> ; return os; 7d: 8b 45 fc mov -0x4(%ebp),%eax } 80: c9 leave 81: c3 ret 00000082 <strcmp>: int strcmp(const char *p, const char *q) { 82: 55 push %ebp 83: 89 e5 mov %esp,%ebp while(*p && *p == *q) 85: eb 08 jmp 8f <strcmp+0xd> p++, q++; 87: 83 45 08 01 addl $0x1,0x8(%ebp) 8b: 83 45 0c 01 addl $0x1,0xc(%ebp) while(*p && *p == *q) 8f: 8b 45 08 mov 0x8(%ebp),%eax 92: 0f b6 00 movzbl (%eax),%eax 95: 84 c0 test %al,%al 97: 74 10 je a9 <strcmp+0x27> 99: 8b 45 08 mov 0x8(%ebp),%eax 9c: 0f b6 10 movzbl (%eax),%edx 9f: 8b 45 0c mov 0xc(%ebp),%eax a2: 0f b6 00 movzbl (%eax),%eax a5: 38 c2 cmp %al,%dl a7: 74 de je 87 <strcmp+0x5> return (uchar)*p - (uchar)*q; a9: 8b 45 08 mov 0x8(%ebp),%eax ac: 0f b6 00 movzbl (%eax),%eax af: 0f b6 d0 movzbl %al,%edx b2: 8b 45 0c mov 0xc(%ebp),%eax b5: 0f b6 00 movzbl (%eax),%eax b8: 0f b6 c8 movzbl %al,%ecx bb: 89 d0 mov %edx,%eax bd: 29 c8 sub %ecx,%eax } bf: 5d pop %ebp c0: c3 ret 000000c1 <strlen>: uint strlen(char *s) { c1: 55 push %ebp c2: 89 e5 mov %esp,%ebp c4: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) c7: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) ce: eb 04 jmp d4 <strlen+0x13> d0: 83 45 fc 01 addl $0x1,-0x4(%ebp) d4: 8b 55 fc mov -0x4(%ebp),%edx d7: 8b 45 08 mov 0x8(%ebp),%eax da: 01 d0 add %edx,%eax dc: 0f b6 00 movzbl (%eax),%eax df: 84 c0 test %al,%al e1: 75 ed jne d0 <strlen+0xf> ; return n; e3: 8b 45 fc mov -0x4(%ebp),%eax } e6: c9 leave e7: c3 ret 000000e8 <memset>: void* memset(void *dst, int c, uint n) { e8: 55 push %ebp e9: 89 e5 mov %esp,%ebp stosb(dst, c, n); eb: 8b 45 10 mov 0x10(%ebp),%eax ee: 50 push %eax ef: ff 75 0c push 0xc(%ebp) f2: ff 75 08 push 0x8(%ebp) f5: e8 32 ff ff ff call 2c <stosb> fa: 83 c4 0c add $0xc,%esp return dst; fd: 8b 45 08 mov 0x8(%ebp),%eax } 100: c9 leave 101: c3 ret 00000102 <strchr>: char* strchr(const char *s, char c) { 102: 55 push %ebp 103: 89 e5 mov %esp,%ebp 105: 83 ec 04 sub $0x4,%esp 108: 8b 45 0c mov 0xc(%ebp),%eax 10b: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 10e: eb 14 jmp 124 <strchr+0x22> if(*s == c) 110: 8b 45 08 mov 0x8(%ebp),%eax 113: 0f b6 00 movzbl (%eax),%eax 116: 38 45 fc cmp %al,-0x4(%ebp) 119: 75 05 jne 120 <strchr+0x1e> return (char*)s; 11b: 8b 45 08 mov 0x8(%ebp),%eax 11e: eb 13 jmp 133 <strchr+0x31> for(; *s; s++) 120: 83 45 08 01 addl $0x1,0x8(%ebp) 124: 8b 45 08 mov 0x8(%ebp),%eax 127: 0f b6 00 movzbl (%eax),%eax 12a: 84 c0 test %al,%al 12c: 75 e2 jne 110 <strchr+0xe> return 0; 12e: b8 00 00 00 00 mov $0x0,%eax } 133: c9 leave 134: c3 ret 00000135 <gets>: char* gets(char *buf, int max) { 135: 55 push %ebp 136: 89 e5 mov %esp,%ebp 138: 83 ec 18 sub $0x18,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 13b: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 142: eb 42 jmp 186 <gets+0x51> cc = read(0, &c, 1); 144: 83 ec 04 sub $0x4,%esp 147: 6a 01 push $0x1 149: 8d 45 ef lea -0x11(%ebp),%eax 14c: 50 push %eax 14d: 6a 00 push $0x0 14f: e8 77 01 00 00 call 2cb <read> 154: 83 c4 10 add $0x10,%esp 157: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 15a: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 15e: 7e 33 jle 193 <gets+0x5e> break; buf[i++] = c; 160: 8b 45 f4 mov -0xc(%ebp),%eax 163: 8d 50 01 lea 0x1(%eax),%edx 166: 89 55 f4 mov %edx,-0xc(%ebp) 169: 89 c2 mov %eax,%edx 16b: 8b 45 08 mov 0x8(%ebp),%eax 16e: 01 c2 add %eax,%edx 170: 0f b6 45 ef movzbl -0x11(%ebp),%eax 174: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 176: 0f b6 45 ef movzbl -0x11(%ebp),%eax 17a: 3c 0a cmp $0xa,%al 17c: 74 16 je 194 <gets+0x5f> 17e: 0f b6 45 ef movzbl -0x11(%ebp),%eax 182: 3c 0d cmp $0xd,%al 184: 74 0e je 194 <gets+0x5f> for(i=0; i+1 < max; ){ 186: 8b 45 f4 mov -0xc(%ebp),%eax 189: 83 c0 01 add $0x1,%eax 18c: 39 45 0c cmp %eax,0xc(%ebp) 18f: 7f b3 jg 144 <gets+0xf> 191: eb 01 jmp 194 <gets+0x5f> break; 193: 90 nop break; } buf[i] = '\0'; 194: 8b 55 f4 mov -0xc(%ebp),%edx 197: 8b 45 08 mov 0x8(%ebp),%eax 19a: 01 d0 add %edx,%eax 19c: c6 00 00 movb $0x0,(%eax) return buf; 19f: 8b 45 08 mov 0x8(%ebp),%eax } 1a2: c9 leave 1a3: c3 ret 000001a4 <stat>: int stat(char *n, struct stat *st) { 1a4: 55 push %ebp 1a5: 89 e5 mov %esp,%ebp 1a7: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 1aa: 83 ec 08 sub $0x8,%esp 1ad: 6a 00 push $0x0 1af: ff 75 08 push 0x8(%ebp) 1b2: e8 3c 01 00 00 call 2f3 <open> 1b7: 83 c4 10 add $0x10,%esp 1ba: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 1bd: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1c1: 79 07 jns 1ca <stat+0x26> return -1; 1c3: b8 ff ff ff ff mov $0xffffffff,%eax 1c8: eb 25 jmp 1ef <stat+0x4b> r = fstat(fd, st); 1ca: 83 ec 08 sub $0x8,%esp 1cd: ff 75 0c push 0xc(%ebp) 1d0: ff 75 f4 push -0xc(%ebp) 1d3: e8 33 01 00 00 call 30b <fstat> 1d8: 83 c4 10 add $0x10,%esp 1db: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 1de: 83 ec 0c sub $0xc,%esp 1e1: ff 75 f4 push -0xc(%ebp) 1e4: e8 f2 00 00 00 call 2db <close> 1e9: 83 c4 10 add $0x10,%esp return r; 1ec: 8b 45 f0 mov -0x10(%ebp),%eax } 1ef: c9 leave 1f0: c3 ret 000001f1 <atoi>: int atoi(const char *s) { 1f1: 55 push %ebp 1f2: 89 e5 mov %esp,%ebp 1f4: 83 ec 10 sub $0x10,%esp int n; n = 0; 1f7: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 1fe: eb 25 jmp 225 <atoi+0x34> n = n*10 + *s++ - '0'; 200: 8b 55 fc mov -0x4(%ebp),%edx 203: 89 d0 mov %edx,%eax 205: c1 e0 02 shl $0x2,%eax 208: 01 d0 add %edx,%eax 20a: 01 c0 add %eax,%eax 20c: 89 c1 mov %eax,%ecx 20e: 8b 45 08 mov 0x8(%ebp),%eax 211: 8d 50 01 lea 0x1(%eax),%edx 214: 89 55 08 mov %edx,0x8(%ebp) 217: 0f b6 00 movzbl (%eax),%eax 21a: 0f be c0 movsbl %al,%eax 21d: 01 c8 add %ecx,%eax 21f: 83 e8 30 sub $0x30,%eax 222: 89 45 fc mov %eax,-0x4(%ebp) while('0' <= *s && *s <= '9') 225: 8b 45 08 mov 0x8(%ebp),%eax 228: 0f b6 00 movzbl (%eax),%eax 22b: 3c 2f cmp $0x2f,%al 22d: 7e 0a jle 239 <atoi+0x48> 22f: 8b 45 08 mov 0x8(%ebp),%eax 232: 0f b6 00 movzbl (%eax),%eax 235: 3c 39 cmp $0x39,%al 237: 7e c7 jle 200 <atoi+0xf> return n; 239: 8b 45 fc mov -0x4(%ebp),%eax } 23c: c9 leave 23d: c3 ret 0000023e <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 23e: 55 push %ebp 23f: 89 e5 mov %esp,%ebp 241: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 244: 8b 45 08 mov 0x8(%ebp),%eax 247: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 24a: 8b 45 0c mov 0xc(%ebp),%eax 24d: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 250: eb 17 jmp 269 <memmove+0x2b> *dst++ = *src++; 252: 8b 55 f8 mov -0x8(%ebp),%edx 255: 8d 42 01 lea 0x1(%edx),%eax 258: 89 45 f8 mov %eax,-0x8(%ebp) 25b: 8b 45 fc mov -0x4(%ebp),%eax 25e: 8d 48 01 lea 0x1(%eax),%ecx 261: 89 4d fc mov %ecx,-0x4(%ebp) 264: 0f b6 12 movzbl (%edx),%edx 267: 88 10 mov %dl,(%eax) while(n-- > 0) 269: 8b 45 10 mov 0x10(%ebp),%eax 26c: 8d 50 ff lea -0x1(%eax),%edx 26f: 89 55 10 mov %edx,0x10(%ebp) 272: 85 c0 test %eax,%eax 274: 7f dc jg 252 <memmove+0x14> return vdst; 276: 8b 45 08 mov 0x8(%ebp),%eax } 279: c9 leave 27a: c3 ret 0000027b <restorer>: 27b: 83 c4 0c add $0xc,%esp 27e: 5a pop %edx 27f: 59 pop %ecx 280: 58 pop %eax 281: c3 ret 00000282 <signal>: "pop %ecx\n\t" "pop %eax\n\t" "ret\n\t"); int signal(int signum, void(*handler)(int)) { 282: 55 push %ebp 283: 89 e5 mov %esp,%ebp 285: 83 ec 08 sub $0x8,%esp signal_restorer(restorer); 288: 83 ec 0c sub $0xc,%esp 28b: 68 7b 02 00 00 push $0x27b 290: e8 ce 00 00 00 call 363 <signal_restorer> 295: 83 c4 10 add $0x10,%esp return signal_register(signum, handler); 298: 83 ec 08 sub $0x8,%esp 29b: ff 75 0c push 0xc(%ebp) 29e: ff 75 08 push 0x8(%ebp) 2a1: e8 b5 00 00 00 call 35b <signal_register> 2a6: 83 c4 10 add $0x10,%esp 2a9: c9 leave 2aa: c3 ret 000002ab <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2ab: b8 01 00 00 00 mov $0x1,%eax 2b0: cd 40 int $0x40 2b2: c3 ret 000002b3 <exit>: SYSCALL(exit) 2b3: b8 02 00 00 00 mov $0x2,%eax 2b8: cd 40 int $0x40 2ba: c3 ret 000002bb <wait>: SYSCALL(wait) 2bb: b8 03 00 00 00 mov $0x3,%eax 2c0: cd 40 int $0x40 2c2: c3 ret 000002c3 <pipe>: SYSCALL(pipe) 2c3: b8 04 00 00 00 mov $0x4,%eax 2c8: cd 40 int $0x40 2ca: c3 ret 000002cb <read>: SYSCALL(read) 2cb: b8 05 00 00 00 mov $0x5,%eax 2d0: cd 40 int $0x40 2d2: c3 ret 000002d3 <write>: SYSCALL(write) 2d3: b8 10 00 00 00 mov $0x10,%eax 2d8: cd 40 int $0x40 2da: c3 ret 000002db <close>: SYSCALL(close) 2db: b8 15 00 00 00 mov $0x15,%eax 2e0: cd 40 int $0x40 2e2: c3 ret 000002e3 <kill>: SYSCALL(kill) 2e3: b8 06 00 00 00 mov $0x6,%eax 2e8: cd 40 int $0x40 2ea: c3 ret 000002eb <exec>: SYSCALL(exec) 2eb: b8 07 00 00 00 mov $0x7,%eax 2f0: cd 40 int $0x40 2f2: c3 ret 000002f3 <open>: SYSCALL(open) 2f3: b8 0f 00 00 00 mov $0xf,%eax 2f8: cd 40 int $0x40 2fa: c3 ret 000002fb <mknod>: SYSCALL(mknod) 2fb: b8 11 00 00 00 mov $0x11,%eax 300: cd 40 int $0x40 302: c3 ret 00000303 <unlink>: SYSCALL(unlink) 303: b8 12 00 00 00 mov $0x12,%eax 308: cd 40 int $0x40 30a: c3 ret 0000030b <fstat>: SYSCALL(fstat) 30b: b8 08 00 00 00 mov $0x8,%eax 310: cd 40 int $0x40 312: c3 ret 00000313 <link>: SYSCALL(link) 313: b8 13 00 00 00 mov $0x13,%eax 318: cd 40 int $0x40 31a: c3 ret 0000031b <mkdir>: SYSCALL(mkdir) 31b: b8 14 00 00 00 mov $0x14,%eax 320: cd 40 int $0x40 322: c3 ret 00000323 <chdir>: SYSCALL(chdir) 323: b8 09 00 00 00 mov $0x9,%eax 328: cd 40 int $0x40 32a: c3 ret 0000032b <dup>: SYSCALL(dup) 32b: b8 0a 00 00 00 mov $0xa,%eax 330: cd 40 int $0x40 332: c3 ret 00000333 <getpid>: SYSCALL(getpid) 333: b8 0b 00 00 00 mov $0xb,%eax 338: cd 40 int $0x40 33a: c3 ret 0000033b <sbrk>: SYSCALL(sbrk) 33b: b8 0c 00 00 00 mov $0xc,%eax 340: cd 40 int $0x40 342: c3 ret 00000343 <sleep>: SYSCALL(sleep) 343: b8 0d 00 00 00 mov $0xd,%eax 348: cd 40 int $0x40 34a: c3 ret 0000034b <uptime>: SYSCALL(uptime) 34b: b8 0e 00 00 00 mov $0xe,%eax 350: cd 40 int $0x40 352: c3 ret 00000353 <halt>: SYSCALL(halt) 353: b8 16 00 00 00 mov $0x16,%eax 358: cd 40 int $0x40 35a: c3 ret 0000035b <signal_register>: SYSCALL(signal_register) 35b: b8 17 00 00 00 mov $0x17,%eax 360: cd 40 int $0x40 362: c3 ret 00000363 <signal_restorer>: SYSCALL(signal_restorer) 363: b8 18 00 00 00 mov $0x18,%eax 368: cd 40 int $0x40 36a: c3 ret 0000036b <mprotect>: SYSCALL(mprotect) 36b: b8 19 00 00 00 mov $0x19,%eax 370: cd 40 int $0x40 372: c3 ret 00000373 <cowfork>: SYSCALL(cowfork) 373: b8 1a 00 00 00 mov $0x1a,%eax 378: cd 40 int $0x40 37a: c3 ret 0000037b <dsbrk>: SYSCALL(dsbrk) 37b: b8 1b 00 00 00 mov $0x1b,%eax 380: cd 40 int $0x40 382: c3 ret 00000383 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 383: 55 push %ebp 384: 89 e5 mov %esp,%ebp 386: 83 ec 18 sub $0x18,%esp 389: 8b 45 0c mov 0xc(%ebp),%eax 38c: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 38f: 83 ec 04 sub $0x4,%esp 392: 6a 01 push $0x1 394: 8d 45 f4 lea -0xc(%ebp),%eax 397: 50 push %eax 398: ff 75 08 push 0x8(%ebp) 39b: e8 33 ff ff ff call 2d3 <write> 3a0: 83 c4 10 add $0x10,%esp } 3a3: 90 nop 3a4: c9 leave 3a5: c3 ret 000003a6 <printint>: static void printint(int fd, int xx, int base, int sgn) { 3a6: 55 push %ebp 3a7: 89 e5 mov %esp,%ebp 3a9: 83 ec 28 sub $0x28,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 3ac: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 3b3: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3b7: 74 17 je 3d0 <printint+0x2a> 3b9: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 3bd: 79 11 jns 3d0 <printint+0x2a> neg = 1; 3bf: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 3c6: 8b 45 0c mov 0xc(%ebp),%eax 3c9: f7 d8 neg %eax 3cb: 89 45 ec mov %eax,-0x14(%ebp) 3ce: eb 06 jmp 3d6 <printint+0x30> } else { x = xx; 3d0: 8b 45 0c mov 0xc(%ebp),%eax 3d3: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3d6: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 3dd: 8b 4d 10 mov 0x10(%ebp),%ecx 3e0: 8b 45 ec mov -0x14(%ebp),%eax 3e3: ba 00 00 00 00 mov $0x0,%edx 3e8: f7 f1 div %ecx 3ea: 89 d1 mov %edx,%ecx 3ec: 8b 45 f4 mov -0xc(%ebp),%eax 3ef: 8d 50 01 lea 0x1(%eax),%edx 3f2: 89 55 f4 mov %edx,-0xc(%ebp) 3f5: 0f b6 91 18 08 00 00 movzbl 0x818(%ecx),%edx 3fc: 88 54 05 dc mov %dl,-0x24(%ebp,%eax,1) }while((x /= base) != 0); 400: 8b 4d 10 mov 0x10(%ebp),%ecx 403: 8b 45 ec mov -0x14(%ebp),%eax 406: ba 00 00 00 00 mov $0x0,%edx 40b: f7 f1 div %ecx 40d: 89 45 ec mov %eax,-0x14(%ebp) 410: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 414: 75 c7 jne 3dd <printint+0x37> if(neg) 416: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 41a: 74 2d je 449 <printint+0xa3> buf[i++] = '-'; 41c: 8b 45 f4 mov -0xc(%ebp),%eax 41f: 8d 50 01 lea 0x1(%eax),%edx 422: 89 55 f4 mov %edx,-0xc(%ebp) 425: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 42a: eb 1d jmp 449 <printint+0xa3> putc(fd, buf[i]); 42c: 8d 55 dc lea -0x24(%ebp),%edx 42f: 8b 45 f4 mov -0xc(%ebp),%eax 432: 01 d0 add %edx,%eax 434: 0f b6 00 movzbl (%eax),%eax 437: 0f be c0 movsbl %al,%eax 43a: 83 ec 08 sub $0x8,%esp 43d: 50 push %eax 43e: ff 75 08 push 0x8(%ebp) 441: e8 3d ff ff ff call 383 <putc> 446: 83 c4 10 add $0x10,%esp while(--i >= 0) 449: 83 6d f4 01 subl $0x1,-0xc(%ebp) 44d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 451: 79 d9 jns 42c <printint+0x86> } 453: 90 nop 454: 90 nop 455: c9 leave 456: c3 ret 00000457 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 457: 55 push %ebp 458: 89 e5 mov %esp,%ebp 45a: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 45d: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 464: 8d 45 0c lea 0xc(%ebp),%eax 467: 83 c0 04 add $0x4,%eax 46a: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 46d: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 474: e9 59 01 00 00 jmp 5d2 <printf+0x17b> c = fmt[i] & 0xff; 479: 8b 55 0c mov 0xc(%ebp),%edx 47c: 8b 45 f0 mov -0x10(%ebp),%eax 47f: 01 d0 add %edx,%eax 481: 0f b6 00 movzbl (%eax),%eax 484: 0f be c0 movsbl %al,%eax 487: 25 ff 00 00 00 and $0xff,%eax 48c: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 48f: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 493: 75 2c jne 4c1 <printf+0x6a> if(c == '%'){ 495: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 499: 75 0c jne 4a7 <printf+0x50> state = '%'; 49b: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 4a2: e9 27 01 00 00 jmp 5ce <printf+0x177> } else { putc(fd, c); 4a7: 8b 45 e4 mov -0x1c(%ebp),%eax 4aa: 0f be c0 movsbl %al,%eax 4ad: 83 ec 08 sub $0x8,%esp 4b0: 50 push %eax 4b1: ff 75 08 push 0x8(%ebp) 4b4: e8 ca fe ff ff call 383 <putc> 4b9: 83 c4 10 add $0x10,%esp 4bc: e9 0d 01 00 00 jmp 5ce <printf+0x177> } } else if(state == '%'){ 4c1: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 4c5: 0f 85 03 01 00 00 jne 5ce <printf+0x177> if(c == 'd'){ 4cb: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 4cf: 75 1e jne 4ef <printf+0x98> printint(fd, *ap, 10, 1); 4d1: 8b 45 e8 mov -0x18(%ebp),%eax 4d4: 8b 00 mov (%eax),%eax 4d6: 6a 01 push $0x1 4d8: 6a 0a push $0xa 4da: 50 push %eax 4db: ff 75 08 push 0x8(%ebp) 4de: e8 c3 fe ff ff call 3a6 <printint> 4e3: 83 c4 10 add $0x10,%esp ap++; 4e6: 83 45 e8 04 addl $0x4,-0x18(%ebp) 4ea: e9 d8 00 00 00 jmp 5c7 <printf+0x170> } else if(c == 'x' || c == 'p'){ 4ef: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 4f3: 74 06 je 4fb <printf+0xa4> 4f5: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 4f9: 75 1e jne 519 <printf+0xc2> printint(fd, *ap, 16, 0); 4fb: 8b 45 e8 mov -0x18(%ebp),%eax 4fe: 8b 00 mov (%eax),%eax 500: 6a 00 push $0x0 502: 6a 10 push $0x10 504: 50 push %eax 505: ff 75 08 push 0x8(%ebp) 508: e8 99 fe ff ff call 3a6 <printint> 50d: 83 c4 10 add $0x10,%esp ap++; 510: 83 45 e8 04 addl $0x4,-0x18(%ebp) 514: e9 ae 00 00 00 jmp 5c7 <printf+0x170> } else if(c == 's'){ 519: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 51d: 75 43 jne 562 <printf+0x10b> s = (char*)*ap; 51f: 8b 45 e8 mov -0x18(%ebp),%eax 522: 8b 00 mov (%eax),%eax 524: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 527: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 52b: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 52f: 75 25 jne 556 <printf+0xff> s = "(null)"; 531: c7 45 f4 0e 08 00 00 movl $0x80e,-0xc(%ebp) while(*s != 0){ 538: eb 1c jmp 556 <printf+0xff> putc(fd, *s); 53a: 8b 45 f4 mov -0xc(%ebp),%eax 53d: 0f b6 00 movzbl (%eax),%eax 540: 0f be c0 movsbl %al,%eax 543: 83 ec 08 sub $0x8,%esp 546: 50 push %eax 547: ff 75 08 push 0x8(%ebp) 54a: e8 34 fe ff ff call 383 <putc> 54f: 83 c4 10 add $0x10,%esp s++; 552: 83 45 f4 01 addl $0x1,-0xc(%ebp) while(*s != 0){ 556: 8b 45 f4 mov -0xc(%ebp),%eax 559: 0f b6 00 movzbl (%eax),%eax 55c: 84 c0 test %al,%al 55e: 75 da jne 53a <printf+0xe3> 560: eb 65 jmp 5c7 <printf+0x170> } } else if(c == 'c'){ 562: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 566: 75 1d jne 585 <printf+0x12e> putc(fd, *ap); 568: 8b 45 e8 mov -0x18(%ebp),%eax 56b: 8b 00 mov (%eax),%eax 56d: 0f be c0 movsbl %al,%eax 570: 83 ec 08 sub $0x8,%esp 573: 50 push %eax 574: ff 75 08 push 0x8(%ebp) 577: e8 07 fe ff ff call 383 <putc> 57c: 83 c4 10 add $0x10,%esp ap++; 57f: 83 45 e8 04 addl $0x4,-0x18(%ebp) 583: eb 42 jmp 5c7 <printf+0x170> } else if(c == '%'){ 585: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 589: 75 17 jne 5a2 <printf+0x14b> putc(fd, c); 58b: 8b 45 e4 mov -0x1c(%ebp),%eax 58e: 0f be c0 movsbl %al,%eax 591: 83 ec 08 sub $0x8,%esp 594: 50 push %eax 595: ff 75 08 push 0x8(%ebp) 598: e8 e6 fd ff ff call 383 <putc> 59d: 83 c4 10 add $0x10,%esp 5a0: eb 25 jmp 5c7 <printf+0x170> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5a2: 83 ec 08 sub $0x8,%esp 5a5: 6a 25 push $0x25 5a7: ff 75 08 push 0x8(%ebp) 5aa: e8 d4 fd ff ff call 383 <putc> 5af: 83 c4 10 add $0x10,%esp putc(fd, c); 5b2: 8b 45 e4 mov -0x1c(%ebp),%eax 5b5: 0f be c0 movsbl %al,%eax 5b8: 83 ec 08 sub $0x8,%esp 5bb: 50 push %eax 5bc: ff 75 08 push 0x8(%ebp) 5bf: e8 bf fd ff ff call 383 <putc> 5c4: 83 c4 10 add $0x10,%esp } state = 0; 5c7: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) for(i = 0; fmt[i]; i++){ 5ce: 83 45 f0 01 addl $0x1,-0x10(%ebp) 5d2: 8b 55 0c mov 0xc(%ebp),%edx 5d5: 8b 45 f0 mov -0x10(%ebp),%eax 5d8: 01 d0 add %edx,%eax 5da: 0f b6 00 movzbl (%eax),%eax 5dd: 84 c0 test %al,%al 5df: 0f 85 94 fe ff ff jne 479 <printf+0x22> } } } 5e5: 90 nop 5e6: 90 nop 5e7: c9 leave 5e8: c3 ret 000005e9 <free>: static Header base; static Header *freep; void free(void *ap) { 5e9: 55 push %ebp 5ea: 89 e5 mov %esp,%ebp 5ec: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 5ef: 8b 45 08 mov 0x8(%ebp),%eax 5f2: 83 e8 08 sub $0x8,%eax 5f5: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5f8: a1 34 08 00 00 mov 0x834,%eax 5fd: 89 45 fc mov %eax,-0x4(%ebp) 600: eb 24 jmp 626 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 602: 8b 45 fc mov -0x4(%ebp),%eax 605: 8b 00 mov (%eax),%eax 607: 39 45 fc cmp %eax,-0x4(%ebp) 60a: 72 12 jb 61e <free+0x35> 60c: 8b 45 f8 mov -0x8(%ebp),%eax 60f: 3b 45 fc cmp -0x4(%ebp),%eax 612: 77 24 ja 638 <free+0x4f> 614: 8b 45 fc mov -0x4(%ebp),%eax 617: 8b 00 mov (%eax),%eax 619: 39 45 f8 cmp %eax,-0x8(%ebp) 61c: 72 1a jb 638 <free+0x4f> for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 61e: 8b 45 fc mov -0x4(%ebp),%eax 621: 8b 00 mov (%eax),%eax 623: 89 45 fc mov %eax,-0x4(%ebp) 626: 8b 45 f8 mov -0x8(%ebp),%eax 629: 3b 45 fc cmp -0x4(%ebp),%eax 62c: 76 d4 jbe 602 <free+0x19> 62e: 8b 45 fc mov -0x4(%ebp),%eax 631: 8b 00 mov (%eax),%eax 633: 39 45 f8 cmp %eax,-0x8(%ebp) 636: 73 ca jae 602 <free+0x19> break; if(bp + bp->s.size == p->s.ptr){ 638: 8b 45 f8 mov -0x8(%ebp),%eax 63b: 8b 40 04 mov 0x4(%eax),%eax 63e: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 645: 8b 45 f8 mov -0x8(%ebp),%eax 648: 01 c2 add %eax,%edx 64a: 8b 45 fc mov -0x4(%ebp),%eax 64d: 8b 00 mov (%eax),%eax 64f: 39 c2 cmp %eax,%edx 651: 75 24 jne 677 <free+0x8e> bp->s.size += p->s.ptr->s.size; 653: 8b 45 f8 mov -0x8(%ebp),%eax 656: 8b 50 04 mov 0x4(%eax),%edx 659: 8b 45 fc mov -0x4(%ebp),%eax 65c: 8b 00 mov (%eax),%eax 65e: 8b 40 04 mov 0x4(%eax),%eax 661: 01 c2 add %eax,%edx 663: 8b 45 f8 mov -0x8(%ebp),%eax 666: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 669: 8b 45 fc mov -0x4(%ebp),%eax 66c: 8b 00 mov (%eax),%eax 66e: 8b 10 mov (%eax),%edx 670: 8b 45 f8 mov -0x8(%ebp),%eax 673: 89 10 mov %edx,(%eax) 675: eb 0a jmp 681 <free+0x98> } else bp->s.ptr = p->s.ptr; 677: 8b 45 fc mov -0x4(%ebp),%eax 67a: 8b 10 mov (%eax),%edx 67c: 8b 45 f8 mov -0x8(%ebp),%eax 67f: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 681: 8b 45 fc mov -0x4(%ebp),%eax 684: 8b 40 04 mov 0x4(%eax),%eax 687: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 68e: 8b 45 fc mov -0x4(%ebp),%eax 691: 01 d0 add %edx,%eax 693: 39 45 f8 cmp %eax,-0x8(%ebp) 696: 75 20 jne 6b8 <free+0xcf> p->s.size += bp->s.size; 698: 8b 45 fc mov -0x4(%ebp),%eax 69b: 8b 50 04 mov 0x4(%eax),%edx 69e: 8b 45 f8 mov -0x8(%ebp),%eax 6a1: 8b 40 04 mov 0x4(%eax),%eax 6a4: 01 c2 add %eax,%edx 6a6: 8b 45 fc mov -0x4(%ebp),%eax 6a9: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6ac: 8b 45 f8 mov -0x8(%ebp),%eax 6af: 8b 10 mov (%eax),%edx 6b1: 8b 45 fc mov -0x4(%ebp),%eax 6b4: 89 10 mov %edx,(%eax) 6b6: eb 08 jmp 6c0 <free+0xd7> } else p->s.ptr = bp; 6b8: 8b 45 fc mov -0x4(%ebp),%eax 6bb: 8b 55 f8 mov -0x8(%ebp),%edx 6be: 89 10 mov %edx,(%eax) freep = p; 6c0: 8b 45 fc mov -0x4(%ebp),%eax 6c3: a3 34 08 00 00 mov %eax,0x834 } 6c8: 90 nop 6c9: c9 leave 6ca: c3 ret 000006cb <morecore>: static Header* morecore(uint nu) { 6cb: 55 push %ebp 6cc: 89 e5 mov %esp,%ebp 6ce: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if(nu < 4096) 6d1: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 6d8: 77 07 ja 6e1 <morecore+0x16> nu = 4096; 6da: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 6e1: 8b 45 08 mov 0x8(%ebp),%eax 6e4: c1 e0 03 shl $0x3,%eax 6e7: 83 ec 0c sub $0xc,%esp 6ea: 50 push %eax 6eb: e8 4b fc ff ff call 33b <sbrk> 6f0: 83 c4 10 add $0x10,%esp 6f3: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 6f6: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 6fa: 75 07 jne 703 <morecore+0x38> return 0; 6fc: b8 00 00 00 00 mov $0x0,%eax 701: eb 26 jmp 729 <morecore+0x5e> hp = (Header*)p; 703: 8b 45 f4 mov -0xc(%ebp),%eax 706: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 709: 8b 45 f0 mov -0x10(%ebp),%eax 70c: 8b 55 08 mov 0x8(%ebp),%edx 70f: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 712: 8b 45 f0 mov -0x10(%ebp),%eax 715: 83 c0 08 add $0x8,%eax 718: 83 ec 0c sub $0xc,%esp 71b: 50 push %eax 71c: e8 c8 fe ff ff call 5e9 <free> 721: 83 c4 10 add $0x10,%esp return freep; 724: a1 34 08 00 00 mov 0x834,%eax } 729: c9 leave 72a: c3 ret 0000072b <malloc>: void* malloc(uint nbytes) { 72b: 55 push %ebp 72c: 89 e5 mov %esp,%ebp 72e: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 731: 8b 45 08 mov 0x8(%ebp),%eax 734: 83 c0 07 add $0x7,%eax 737: c1 e8 03 shr $0x3,%eax 73a: 83 c0 01 add $0x1,%eax 73d: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 740: a1 34 08 00 00 mov 0x834,%eax 745: 89 45 f0 mov %eax,-0x10(%ebp) 748: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 74c: 75 23 jne 771 <malloc+0x46> base.s.ptr = freep = prevp = &base; 74e: c7 45 f0 2c 08 00 00 movl $0x82c,-0x10(%ebp) 755: 8b 45 f0 mov -0x10(%ebp),%eax 758: a3 34 08 00 00 mov %eax,0x834 75d: a1 34 08 00 00 mov 0x834,%eax 762: a3 2c 08 00 00 mov %eax,0x82c base.s.size = 0; 767: c7 05 30 08 00 00 00 movl $0x0,0x830 76e: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 771: 8b 45 f0 mov -0x10(%ebp),%eax 774: 8b 00 mov (%eax),%eax 776: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 779: 8b 45 f4 mov -0xc(%ebp),%eax 77c: 8b 40 04 mov 0x4(%eax),%eax 77f: 39 45 ec cmp %eax,-0x14(%ebp) 782: 77 4d ja 7d1 <malloc+0xa6> if(p->s.size == nunits) 784: 8b 45 f4 mov -0xc(%ebp),%eax 787: 8b 40 04 mov 0x4(%eax),%eax 78a: 39 45 ec cmp %eax,-0x14(%ebp) 78d: 75 0c jne 79b <malloc+0x70> prevp->s.ptr = p->s.ptr; 78f: 8b 45 f4 mov -0xc(%ebp),%eax 792: 8b 10 mov (%eax),%edx 794: 8b 45 f0 mov -0x10(%ebp),%eax 797: 89 10 mov %edx,(%eax) 799: eb 26 jmp 7c1 <malloc+0x96> else { p->s.size -= nunits; 79b: 8b 45 f4 mov -0xc(%ebp),%eax 79e: 8b 40 04 mov 0x4(%eax),%eax 7a1: 2b 45 ec sub -0x14(%ebp),%eax 7a4: 89 c2 mov %eax,%edx 7a6: 8b 45 f4 mov -0xc(%ebp),%eax 7a9: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 7ac: 8b 45 f4 mov -0xc(%ebp),%eax 7af: 8b 40 04 mov 0x4(%eax),%eax 7b2: c1 e0 03 shl $0x3,%eax 7b5: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 7b8: 8b 45 f4 mov -0xc(%ebp),%eax 7bb: 8b 55 ec mov -0x14(%ebp),%edx 7be: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 7c1: 8b 45 f0 mov -0x10(%ebp),%eax 7c4: a3 34 08 00 00 mov %eax,0x834 return (void*)(p + 1); 7c9: 8b 45 f4 mov -0xc(%ebp),%eax 7cc: 83 c0 08 add $0x8,%eax 7cf: eb 3b jmp 80c <malloc+0xe1> } if(p == freep) 7d1: a1 34 08 00 00 mov 0x834,%eax 7d6: 39 45 f4 cmp %eax,-0xc(%ebp) 7d9: 75 1e jne 7f9 <malloc+0xce> if((p = morecore(nunits)) == 0) 7db: 83 ec 0c sub $0xc,%esp 7de: ff 75 ec push -0x14(%ebp) 7e1: e8 e5 fe ff ff call 6cb <morecore> 7e6: 83 c4 10 add $0x10,%esp 7e9: 89 45 f4 mov %eax,-0xc(%ebp) 7ec: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 7f0: 75 07 jne 7f9 <malloc+0xce> return 0; 7f2: b8 00 00 00 00 mov $0x0,%eax 7f7: eb 13 jmp 80c <malloc+0xe1> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 7f9: 8b 45 f4 mov -0xc(%ebp),%eax 7fc: 89 45 f0 mov %eax,-0x10(%ebp) 7ff: 8b 45 f4 mov -0xc(%ebp),%eax 802: 8b 00 mov (%eax),%eax 804: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 807: e9 6d ff ff ff jmp 779 <malloc+0x4e> } } 80c: c9 leave 80d: c3 ret
%define sys_write 0x04 %define sys_rt_sigaction 0x43 %define sys_pause 0x1d %define sys_exit 0x01 %define sys_rt_sigreturn 0xad %define SIGTERM 0x0f %define SIGINT 0x02 %define SIGSEGV 0xb %define STDOUT 0x01 %define SA_RESTORER 0x04000000 ; Definition of sigaction struct for sys_rt_sigaction struc sigaction .sa_handler resd 1 .sa_flags resd 1 .sa_restorer resd 1 .sa_mask resd 1 endstruc section .data ; Message shown when a int 0x80 fails error_msg db 'int 0x80 error', 0x0a error_msg_len equ $ - error_msg ; Message shown when SIGTERM is received sigterm_msg db 'SIGTERM received', 0x0a sigterm_msg_len equ $ - sigterm_msg section .bss act resb sigaction_size val resd 1 section .text global _start _start: mov dword [act + sigaction.sa_handler], handler mov [act + sigaction.sa_flags], DWORD SA_RESTORER mov dword [act + sigaction.sa_restorer], restorer mov eax, sys_rt_sigaction ;mov ebx, SIGINT mov ebx, SIGTERM mov ecx, act xor edx, edx int 0x80 cmp eax, 0 jne error mov eax, sys_pause int 0x80 jmp exit error: mov eax, sys_write mov ebx, STDOUT mov ecx, error_msg mov edx, error_msg_len int 0x80 mov dword [val], 0x01 exit: mov eax, sys_exit mov ebx, [val] int 0x80 handler: mov eax, sys_write mov ebx, STDOUT mov ecx, sigint_msg mov edx, sigint_msg_len int 0x80 ret restorer: mov eax, sys_rt_sigreturn int 0x80
<% from pwnlib.shellcraft.thumb.linux import syscall %> <%page args="which, value"/> <%docstring> Invokes the syscall getitimer. See 'man 2 getitimer' for more information. Arguments: which(itimer_which_t): which value(itimerval): value </%docstring> ${syscall('SYS_getitimer', which, value)}
#include "co/unitest.h" #include "co/os.h" namespace test { DEF_test(os) { DEF_case(env) { EXPECT_EQ(os::env("CO_TEST"), fastring()); os::env("CO_TEST", "777"); EXPECT_EQ(os::env("CO_TEST"), "777"); os::env("CO_TEST", ""); EXPECT_EQ(os::env("CO_TEST"), fastring()); } DEF_case(homedir) { EXPECT_NE(os::homedir(), fastring()); } DEF_case(cwd) { EXPECT_NE(os::cwd(), fastring()); } DEF_case(exename) { EXPECT_NE(os::exepath(), fastring()); EXPECT_NE(os::exedir(), fastring()); EXPECT_NE(os::exename(), fastring()); EXPECT(os::exepath().starts_with(os::exedir())); EXPECT(os::exepath().ends_with(os::exename())); EXPECT(os::exename().starts_with("unitest")); } DEF_case(pid) { EXPECT_GE(os::pid(), 0); } DEF_case(cpunum) { EXPECT_GT(os::cpunum(), 0); } } } // namespace test
;***************************************************************************** ;* MMX optimized DSP utils ;***************************************************************************** ;* Copyright (c) 2000, 2001 Fabrice Bellard ;* Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with FFmpeg; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;***************************************************************************** %include "libavutil/x86/x86util.asm" SECTION .text %macro DIFF_PIXELS_1 4 movh %1, %3 movh %2, %4 punpcklbw %2, %1 punpcklbw %1, %1 psubw %1, %2 %endmacro ; %1=uint8_t *pix1, %2=uint8_t *pix2, %3=static offset, %4=stride, %5=stride*3 ; %6=temporary storage location ; this macro requires $mmsize stack space (aligned) on %6 (except on SSE+x86-64) %macro DIFF_PIXELS_8 6 DIFF_PIXELS_1 m0, m7, [%1 +%3], [%2 +%3] DIFF_PIXELS_1 m1, m7, [%1+%4 +%3], [%2+%4 +%3] DIFF_PIXELS_1 m2, m7, [%1+%4*2+%3], [%2+%4*2+%3] add %1, %5 add %2, %5 DIFF_PIXELS_1 m3, m7, [%1 +%3], [%2 +%3] DIFF_PIXELS_1 m4, m7, [%1+%4 +%3], [%2+%4 +%3] DIFF_PIXELS_1 m5, m7, [%1+%4*2+%3], [%2+%4*2+%3] DIFF_PIXELS_1 m6, m7, [%1+%5 +%3], [%2+%5 +%3] %ifdef m8 DIFF_PIXELS_1 m7, m8, [%1+%4*4+%3], [%2+%4*4+%3] %else mova [%6], m0 DIFF_PIXELS_1 m7, m0, [%1+%4*4+%3], [%2+%4*4+%3] mova m0, [%6] %endif sub %1, %5 sub %2, %5 %endmacro %macro HADAMARD8 0 SUMSUB_BADC w, 0, 1, 2, 3 SUMSUB_BADC w, 4, 5, 6, 7 SUMSUB_BADC w, 0, 2, 1, 3 SUMSUB_BADC w, 4, 6, 5, 7 SUMSUB_BADC w, 0, 4, 1, 5 SUMSUB_BADC w, 2, 6, 3, 7 %endmacro %macro ABS1_SUM 3 ABS1 %1, %2 paddusw %3, %1 %endmacro %macro ABS2_SUM 6 ABS2 %1, %2, %3, %4 paddusw %5, %1 paddusw %6, %2 %endmacro %macro ABS_SUM_8x8_64 1 ABS2 m0, m1, m8, m9 ABS2_SUM m2, m3, m8, m9, m0, m1 ABS2_SUM m4, m5, m8, m9, m0, m1 ABS2_SUM m6, m7, m8, m9, m0, m1 paddusw m0, m1 %endmacro %macro ABS_SUM_8x8_32 1 mova [%1], m7 ABS1 m0, m7 ABS1 m1, m7 ABS1_SUM m2, m7, m0 ABS1_SUM m3, m7, m1 ABS1_SUM m4, m7, m0 ABS1_SUM m5, m7, m1 ABS1_SUM m6, m7, m0 mova m2, [%1] ABS1_SUM m2, m7, m1 paddusw m0, m1 %endmacro ; FIXME: HSUM saturates at 64k, while an 8x8 hadamard or dct block can get up to ; about 100k on extreme inputs. But that's very unlikely to occur in natural video, ; and it's even more unlikely to not have any alternative mvs/modes with lower cost. %macro HSUM 3 %if cpuflag(sse2) movhlps %2, %1 paddusw %1, %2 pshuflw %2, %1, 0xE paddusw %1, %2 pshuflw %2, %1, 0x1 paddusw %1, %2 movd %3, %1 %elif cpuflag(mmxext) pshufw %2, %1, 0xE paddusw %1, %2 pshufw %2, %1, 0x1 paddusw %1, %2 movd %3, %1 %elif cpuflag(mmx) mova %2, %1 psrlq %1, 32 paddusw %1, %2 mova %2, %1 psrlq %1, 16 paddusw %1, %2 movd %3, %1 %endif %endmacro %macro STORE4 5 mova [%1+mmsize*0], %2 mova [%1+mmsize*1], %3 mova [%1+mmsize*2], %4 mova [%1+mmsize*3], %5 %endmacro %macro LOAD4 5 mova %2, [%1+mmsize*0] mova %3, [%1+mmsize*1] mova %4, [%1+mmsize*2] mova %5, [%1+mmsize*3] %endmacro %macro hadamard8_16_wrapper 2 cglobal hadamard8_diff, 4, 4, %1 %ifndef m8 %assign pad %2*mmsize-(4+stack_offset&(mmsize-1)) SUB rsp, pad %endif call hadamard8x8_diff %+ SUFFIX %ifndef m8 ADD rsp, pad %endif RET cglobal hadamard8_diff16, 5, 6, %1 %ifndef m8 %assign pad %2*mmsize-(4+stack_offset&(mmsize-1)) SUB rsp, pad %endif call hadamard8x8_diff %+ SUFFIX mov r5d, eax add r1, 8 add r2, 8 call hadamard8x8_diff %+ SUFFIX add r5d, eax cmp r4d, 16 jne .done lea r1, [r1+r3*8-8] lea r2, [r2+r3*8-8] call hadamard8x8_diff %+ SUFFIX add r5d, eax add r1, 8 add r2, 8 call hadamard8x8_diff %+ SUFFIX add r5d, eax .done: mov eax, r5d %ifndef m8 ADD rsp, pad %endif RET %endmacro %macro HADAMARD8_DIFF 0-1 %if cpuflag(sse2) hadamard8x8_diff %+ SUFFIX: lea r0, [r3*3] DIFF_PIXELS_8 r1, r2, 0, r3, r0, rsp+gprsize HADAMARD8 %if ARCH_X86_64 TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, 8 %else TRANSPOSE8x8W 0, 1, 2, 3, 4, 5, 6, 7, [rsp+gprsize], [rsp+mmsize+gprsize] %endif HADAMARD8 ABS_SUM_8x8 rsp+gprsize HSUM m0, m1, eax and eax, 0xFFFF ret hadamard8_16_wrapper %1, 3 %elif cpuflag(mmx) ALIGN 16 ; int ff_hadamard8_diff_ ## cpu(MpegEncContext *s, uint8_t *src1, ; uint8_t *src2, int stride, int h) ; r0 = void *s = unused, int h = unused (always 8) ; note how r1, r2 and r3 are not clobbered in this function, so 16x16 ; can simply call this 2x2x (and that's why we access rsp+gprsize ; everywhere, which is rsp of calling func hadamard8x8_diff %+ SUFFIX: lea r0, [r3*3] ; first 4x8 pixels DIFF_PIXELS_8 r1, r2, 0, r3, r0, rsp+gprsize+0x60 HADAMARD8 mova [rsp+gprsize+0x60], m7 TRANSPOSE4x4W 0, 1, 2, 3, 7 STORE4 rsp+gprsize, m0, m1, m2, m3 mova m7, [rsp+gprsize+0x60] TRANSPOSE4x4W 4, 5, 6, 7, 0 STORE4 rsp+gprsize+0x40, m4, m5, m6, m7 ; second 4x8 pixels DIFF_PIXELS_8 r1, r2, 4, r3, r0, rsp+gprsize+0x60 HADAMARD8 mova [rsp+gprsize+0x60], m7 TRANSPOSE4x4W 0, 1, 2, 3, 7 STORE4 rsp+gprsize+0x20, m0, m1, m2, m3 mova m7, [rsp+gprsize+0x60] TRANSPOSE4x4W 4, 5, 6, 7, 0 LOAD4 rsp+gprsize+0x40, m0, m1, m2, m3 HADAMARD8 ABS_SUM_8x8_32 rsp+gprsize+0x60 mova [rsp+gprsize+0x60], m0 LOAD4 rsp+gprsize , m0, m1, m2, m3 LOAD4 rsp+gprsize+0x20, m4, m5, m6, m7 HADAMARD8 ABS_SUM_8x8_32 rsp+gprsize paddusw m0, [rsp+gprsize+0x60] HSUM m0, m1, eax and rax, 0xFFFF ret hadamard8_16_wrapper 0, 14 %endif %endmacro INIT_MMX mmx HADAMARD8_DIFF INIT_MMX mmxext HADAMARD8_DIFF INIT_XMM sse2 %if ARCH_X86_64 %define ABS_SUM_8x8 ABS_SUM_8x8_64 %else %define ABS_SUM_8x8 ABS_SUM_8x8_32 %endif HADAMARD8_DIFF 10 INIT_XMM ssse3 %define ABS_SUM_8x8 ABS_SUM_8x8_64 HADAMARD8_DIFF 9 INIT_XMM sse2 ; int ff_sse16_sse2(MpegEncContext *v, uint8_t *pix1, uint8_t *pix2, ; int line_size, int h); cglobal sse16, 5, 5, 8 shr r4d, 1 pxor m0, m0 ; mm0 = 0 pxor m7, m7 ; mm7 holds the sum .next2lines: ; FIXME why are these unaligned movs? pix1[] is aligned movu m1, [r1 ] ; mm1 = pix1[0][0-15] movu m2, [r2 ] ; mm2 = pix2[0][0-15] movu m3, [r1+r3] ; mm3 = pix1[1][0-15] movu m4, [r2+r3] ; mm4 = pix2[1][0-15] ; todo: mm1-mm2, mm3-mm4 ; algo: subtract mm1 from mm2 with saturation and vice versa ; OR the result to get the absolute difference mova m5, m1 mova m6, m3 psubusb m1, m2 psubusb m3, m4 psubusb m2, m5 psubusb m4, m6 por m2, m1 por m4, m3 ; now convert to 16-bit vectors so we can square them mova m1, m2 mova m3, m4 punpckhbw m2, m0 punpckhbw m4, m0 punpcklbw m1, m0 ; mm1 not spread over (mm1,mm2) punpcklbw m3, m0 ; mm4 not spread over (mm3,mm4) pmaddwd m2, m2 pmaddwd m4, m4 pmaddwd m1, m1 pmaddwd m3, m3 lea r1, [r1+r3*2] ; pix1 += 2*line_size lea r2, [r2+r3*2] ; pix2 += 2*line_size paddd m1, m2 paddd m3, m4 paddd m7, m1 paddd m7, m3 dec r4 jnz .next2lines mova m1, m7 psrldq m7, 8 ; shift hi qword to lo paddd m7, m1 mova m1, m7 psrldq m7, 4 ; shift hi dword to lo paddd m7, m1 movd eax, m7 ; return value RET INIT_MMX mmx ; void ff_get_pixels_mmx(int16_t *block, const uint8_t *pixels, int line_size) cglobal get_pixels, 3,4 movsxdifnidn r2, r2d add r0, 128 mov r3, -128 pxor m7, m7 .loop: mova m0, [r1] mova m2, [r1+r2] mova m1, m0 mova m3, m2 punpcklbw m0, m7 punpckhbw m1, m7 punpcklbw m2, m7 punpckhbw m3, m7 mova [r0+r3+ 0], m0 mova [r0+r3+ 8], m1 mova [r0+r3+16], m2 mova [r0+r3+24], m3 lea r1, [r1+r2*2] add r3, 32 js .loop REP_RET INIT_XMM sse2 cglobal get_pixels, 3, 4 movsxdifnidn r2, r2d lea r3, [r2*3] pxor m4, m4 movh m0, [r1] movh m1, [r1+r2] movh m2, [r1+r2*2] movh m3, [r1+r3] lea r1, [r1+r2*4] punpcklbw m0, m4 punpcklbw m1, m4 punpcklbw m2, m4 punpcklbw m3, m4 mova [r0], m0 mova [r0+0x10], m1 mova [r0+0x20], m2 mova [r0+0x30], m3 movh m0, [r1] movh m1, [r1+r2*1] movh m2, [r1+r2*2] movh m3, [r1+r3] punpcklbw m0, m4 punpcklbw m1, m4 punpcklbw m2, m4 punpcklbw m3, m4 mova [r0+0x40], m0 mova [r0+0x50], m1 mova [r0+0x60], m2 mova [r0+0x70], m3 RET INIT_MMX mmx ; void ff_diff_pixels_mmx(int16_t *block, const uint8_t *s1, const uint8_t *s2, ; int stride); cglobal diff_pixels, 4,5 movsxdifnidn r3, r3d pxor m7, m7 add r0, 128 mov r4, -128 .loop: mova m0, [r1] mova m2, [r2] mova m1, m0 mova m3, m2 punpcklbw m0, m7 punpckhbw m1, m7 punpcklbw m2, m7 punpckhbw m3, m7 psubw m0, m2 psubw m1, m3 mova [r0+r4+0], m0 mova [r0+r4+8], m1 add r1, r3 add r2, r3 add r4, 16 jne .loop REP_RET INIT_MMX mmx ; int ff_pix_sum16_mmx(uint8_t *pix, int line_size) cglobal pix_sum16, 2, 3 movsxdifnidn r1, r1d mov r2, r1 neg r2 shl r2, 4 sub r0, r2 pxor m7, m7 pxor m6, m6 .loop: mova m0, [r0+r2+0] mova m1, [r0+r2+0] mova m2, [r0+r2+8] mova m3, [r0+r2+8] punpcklbw m0, m7 punpckhbw m1, m7 punpcklbw m2, m7 punpckhbw m3, m7 paddw m1, m0 paddw m3, m2 paddw m3, m1 paddw m6, m3 add r2, r1 js .loop mova m5, m6 psrlq m6, 32 paddw m6, m5 mova m5, m6 psrlq m6, 16 paddw m6, m5 movd eax, m6 and eax, 0xffff RET INIT_MMX mmx ; int ff_pix_norm1_mmx(uint8_t *pix, int line_size) cglobal pix_norm1, 2, 4 movsxdifnidn r1, r1d mov r2, 16 pxor m0, m0 pxor m7, m7 .loop: mova m2, [r0+0] mova m3, [r0+8] mova m1, m2 punpckhbw m1, m0 punpcklbw m2, m0 mova m4, m3 punpckhbw m3, m0 punpcklbw m4, m0 pmaddwd m1, m1 pmaddwd m2, m2 pmaddwd m3, m3 pmaddwd m4, m4 paddd m2, m1 paddd m4, m3 paddd m7, m2 add r0, r1 paddd m7, m4 dec r2 jne .loop mova m1, m7 psrlq m7, 32 paddd m1, m7 movd eax, m1 RET
; A017666: Denominator of sum of reciprocals of divisors of n. ; 1,2,3,4,5,1,7,8,9,5,11,3,13,7,5,16,17,6,19,10,21,11,23,2,25,13,27,1,29,5,31,32,11,17,35,36,37,19,39,4,41,7,43,11,15,23,47,12,49,50,17,26,53,9,55,7,57,29,59,5,61,31,63,64,65,11,67,34,23,35,71,24,73,37,75,19,77,13,79,40,81,41,83,3,85,43,29,22,89,5,13,23,93,47,19,8,97,98,33,100 mov $1,$0 seq $1,9194 ; a(n) = gcd(n, sigma(n)). div $0,$1 add $0,1
; A240567: a(n) = optimal number of tricks to throw in the game of One Round War (with n cards) in order to maximize the expected number of tricks won. ; 1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7 mov $2,$0 mov $0,3 sub $2,2 add $0,$2 lpb $0 trn $3,$0 add $3,$1 sub $0,$3 sub $0,1 trn $0,3 add $1,1 add $3,3 mul $3,2 add $3,2 lpe
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "l1/factorization/solve_V.h" #include "l1/factorization/solve_V_j.h" using Eigen::MatrixXd; using std::unique_ptr; namespace wiberg { SolveV::SolveV() {} SolveV::~SolveV() { } const SolveVj &SolveV::solve_V_j(int i) const { assert(i >= 0); assert(i < size_); return solve_V_j_[i]; } void SolveV::CopyFrom(const SolveV &solve_V) { size_ = solve_V.size(); solve_V_j_.reset(new SolveVj[size_]); for (int i = 0; i < size_; ++i) { solve_V_j_[i].CopyFrom(solve_V.solve_V_j(i)); } V_ = solve_V.V_; } void SolveV::Solve(const MatrixXd &U, const MatrixXd &Y, const MatrixXd &W_hat) { size_ = Y.cols(); solve_V_j_.reset(new SolveVj[size_]); V_ = MatrixXd::Zero(U.cols(), size_); for (int j = 0; j < size_; ++j) { solve_V_j_[j].Solve(U, Y, W_hat, j); V_.col(j) = solve_V_j_[j].V_j(); } } } // namespace wiberg
#include <core/object.hpp> #include "catch.hpp" SCENARIO("We can test objects for intersection with rays", "[core][object]") { GIVEN("a object with the shape of a sphere") { core::object obj; obj.shape = { { 0.0f, 0.0f, 0.0f }, 1.0f }; obj.material = {}; GIVEN("a ray pointing to the object") { auto ray = math::ray3d{ math::point3d{ 0.0f, 0.0f, 2.0f }, math::vector3d{ 0.0f, 0.0f, -1.0f } }; THEN("a intersection is found") { REQUIRE(core::intersects(obj, ray) == true); REQUIRE(core::closest_intersection(obj, ray).is_initialized() == true); } } GIVEN("a ray pointing to the other side") { auto ray = math::ray3d{ math::point3d{ 0.0f, 0.0f, 2.0f }, math::vector3d{ 0.0f, 0.0f, 1.0f } }; THEN("no intersection is found") { REQUIRE(core::intersects(obj, ray) == false); REQUIRE(core::closest_intersection(obj, ray).is_initialized() == false); } } } }
; A093178: If n is even then 1, otherwise n. ; 1,1,1,3,1,5,1,7,1,9,1,11,1,13,1,15,1,17,1,19,1,21,1,23,1,25,1,27,1,29,1,31,1,33,1,35,1,37,1,39,1,41,1,43,1,45,1,47,1,49,1,51,1,53,1,55,1,57,1,59,1,61,1,63,1,65,1,67,1,69,1,71,1,73,1,75,1,77,1,79,1,81,1,83,1,85,1,87,1,89,1,91,1,93,1,95,1,97,1,99 mov $1,$0 mod $1,2 pow $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r8 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x1a8ef, %rax nop cmp %r11, %r11 mov (%rax), %rcx nop nop nop mfence lea addresses_WC_ht+0x19cef, %r14 nop nop nop inc %r8 mov (%r14), %ebx nop nop nop nop nop add %rax, %rax lea addresses_WT_ht+0xc08f, %rsi lea addresses_UC_ht+0x1daff, %rdi nop nop nop xor %rbx, %rbx mov $65, %rcx rep movsq nop dec %rax lea addresses_UC_ht+0xd4ef, %rsi lea addresses_normal_ht+0x148f, %rdi clflush (%rsi) nop nop nop nop nop cmp $21423, %r11 mov $35, %rcx rep movsl nop nop nop nop nop sub $2169, %rbx lea addresses_normal_ht+0x8fcf, %rsi nop nop add $8257, %rcx mov (%rsi), %edi lfence lea addresses_A_ht+0x15b7e, %rsi lea addresses_A_ht+0x1a0b3, %rdi nop inc %r11 mov $24, %rcx rep movsb nop sub $33078, %rbx lea addresses_A_ht+0x5283, %r14 nop nop nop nop sub %rbx, %rbx mov (%r14), %esi nop nop nop inc %rax lea addresses_normal_ht+0x1b46f, %r14 add %rdi, %rdi vmovups (%r14), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %rsi nop nop nop nop and $30801, %r8 lea addresses_A_ht+0x325f, %rsi lea addresses_WC_ht+0x1bcef, %rdi nop nop nop nop cmp %rax, %rax mov $6, %rcx rep movsq nop nop nop nop cmp $52876, %rsi lea addresses_normal_ht+0x17aef, %rbx clflush (%rbx) nop nop nop and $51307, %r11 and $0xffffffffffffffc0, %rbx movaps (%rbx), %xmm6 vpextrq $1, %xmm6, %r14 nop nop nop nop nop add %r8, %r8 lea addresses_A_ht+0x4663, %rsi lea addresses_D_ht+0x2ef7, %rdi nop and %rax, %rax mov $117, %rcx rep movsb nop nop nop nop nop xor %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r8 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %r8 push %rbx push %rdx // Faulty Load mov $0x7235730000000cef, %rbx clflush (%rbx) nop add $1951, %r11 movb (%rbx), %dl lea oracles, %rbx and $0xff, %rdx shlq $12, %rdx mov (%rbx,%rdx,1), %rdx pop %rdx pop %rbx pop %r8 pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': True, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 4, 'size': 8, 'same': False, 'NT': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': True, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': True}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 1, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 2, 'size': 16, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r15 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x175ee, %rsi lea addresses_A_ht+0xb166, %rdi clflush (%rdi) dec %r14 mov $85, %rcx rep movsb nop and %rax, %rax lea addresses_A_ht+0x12840, %rsi lea addresses_UC_ht+0x18e, %rdi nop nop add $42270, %rax mov $85, %rcx rep movsl nop nop nop xor $3313, %rax lea addresses_A_ht+0x25de, %rcx nop nop add %r12, %r12 mov (%rcx), %r14w nop nop nop sub %rcx, %rcx lea addresses_WT_ht+0x988c, %r14 nop nop sub %rbx, %rbx mov (%r14), %r12d nop nop nop sub %r14, %r14 lea addresses_WC_ht+0x1b0ce, %rcx nop nop add %rax, %rax movw $0x6162, (%rcx) add $48862, %r12 lea addresses_WC_ht+0x16b96, %rsi lea addresses_UC_ht+0x1e9a6, %rdi nop nop cmp $48991, %rbx mov $95, %rcx rep movsq nop add %rcx, %rcx lea addresses_normal_ht+0x1660e, %rsi lea addresses_normal_ht+0x17016, %rdi nop nop nop nop and $7508, %r15 mov $68, %rcx rep movsb nop nop nop and %rcx, %rcx lea addresses_normal_ht+0x1d0ce, %rsi nop nop and %rcx, %rcx movw $0x6162, (%rsi) nop and $20312, %rbx lea addresses_normal_ht+0xfece, %rsi lea addresses_UC_ht+0xb462, %rdi nop nop nop nop xor %r15, %r15 mov $40, %rcx rep movsw nop nop nop nop nop and $19015, %r12 lea addresses_D_ht+0x1e76e, %rsi lea addresses_UC_ht+0x1278e, %rdi nop nop nop nop and $28919, %r12 mov $23, %rcx rep movsw nop nop nop nop nop dec %r12 lea addresses_UC_ht+0x1b39e, %r12 nop nop nop inc %rsi movw $0x6162, (%r12) nop nop nop nop nop add $52545, %r12 lea addresses_D_ht+0x1232e, %rdi nop nop nop nop dec %rsi vmovups (%rdi), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $0, %xmm1, %rax nop nop nop add $45726, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r15 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r8 push %rbp push %rcx push %rdi push %rsi // Store lea addresses_A+0x1248e, %r12 nop nop cmp $3862, %r13 mov $0x5152535455565758, %rbp movq %rbp, %xmm0 movups %xmm0, (%r12) add %r8, %r8 // REPMOV lea addresses_RW+0x4f4e, %rsi lea addresses_PSE+0x1e0ce, %rdi clflush (%rsi) nop nop nop nop nop dec %r12 mov $31, %rcx rep movsw nop xor $13683, %r8 // Store lea addresses_D+0xb4ce, %rsi nop nop add %rbp, %rbp movb $0x51, (%rsi) nop nop nop nop sub %r12, %r12 // Store mov $0x46fa500000003a0, %rdi inc %r13 movl $0x51525354, (%rdi) nop nop nop nop cmp %rbp, %rbp // Faulty Load lea addresses_PSE+0x1e0ce, %rdi inc %r8 movups (%rdi), %xmm4 vpextrq $1, %xmm4, %r13 lea oracles, %rbp and $0xff, %r13 shlq $12, %r13 mov (%rbp,%r13,1), %r13 pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_RW'}, 'dst': {'congruent': 0, 'same': True, 'type': 'addresses_PSE'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 10, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 1, 'same': False, 'type': 'addresses_NC'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 3, 'same': True, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 1, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 10, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 5, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
%INCLUDE "lib.h" global _start section .data num1_msg db "First number: ", 0 num2_msg db "Second number: ", 0 num3_msg db "Third number: ", 0 min_msg db "Minimum number is ", 0 max_msg db "Maximum number is ", 0 endl db 10, 0 section .bss inp_buffer resb 12 min_int resd 12 max_int resd 12 section .code _start: puts num1_msg fgets inp_buffer, 12 a2i 12, inp_buffer push eax ; push first number onto stack puts num2_msg fgets inp_buffer, 12 a2i 12, inp_buffer push eax ; push second number onto stack puts num3_msg fgets inp_buffer, 12 a2i 12, inp_buffer push eax ; push third number onto stack push min_int ; push pointer to min_int onto stack push max_int ; push pointer to max_int onto stack call minmax puts endl puts min_msg i2a dword [min_int], inp_buffer puts inp_buffer ; display minimum number puts endl puts max_msg i2a dword [max_int], inp_buffer puts inp_buffer ; display maximum number puts endl mov eax, 1 mov ebx, 0 int 0x80 %DEFINE NUM1 DWORD [EBP + 24] %DEFINE NUM2 DWORD [EBP + 20] %DEFINE NUM3 DWORD [EBP + 16] %DEFINE MIN [EBP + 12] %DEFINE MAX [EBP + 8] ;-------------------------------proc minmax--------------------------------; ; procedure minmax receives three integers and two pointers to variables ; ; min_int and max_int via stack and returns the minimum and the maximum of ; ; the three in min_int and max_int. ; ;--------------------------------------------------------------------------; minmax: enter 0, 0 push eax push ebx max: mov eax, NUM1 ; load EAX with first number cmp eax, NUM2 jg max_next_cmp mov eax, NUM2 ; if second number is greater than first number, load EAX with it max_next_cmp: cmp eax, NUM3 jg max_done mov eax, NUM3 ; if third number is greater than other two, load EAX with it max_done: mov ebx, MAX ; load EBX with pointer to max_int mov [ebx], eax ; save maximum in max_int min: mov eax, NUM1 ; load EAX with first number cmp eax, NUM2 jl min_next_cmp mov eax, NUM2 ; if second number is less than first number, load EAX with it min_next_cmp: cmp eax, NUM3 jl min_done mov eax, NUM3 ; if third number is less than other two, load EAX with it min_done: mov ebx, MIN ; load EBX with pointer to min_int mov [ebx], eax ; save minimum in min_int minmax_done: pop ebx pop eax leave ret 20
* Pointer version error message v0.00  Jun 1988 J.R.Oakley QJUMP * include 'dev8_mac_text' * section language * mktext pver,{Version trop ancienne de l'Interface Pointeur\} * end
;; ml64 Real_x64.asm .code ;; public: void __cdecl Real10::FromDouble(double) ?FromDouble@Real10@@QEAAXN@Z proc sub rsp, 8 movsd qword ptr [rsp],xmm1 fld qword ptr [rsp] fstp tbyte ptr [ecx] add rsp, 8 ret ?FromDouble@Real10@@QEAAXN@Z endp ;; public: void __cdecl Real10::FromFloat(float) ?FromFloat@Real10@@QEAAXM@Z proc sub rsp, 8 movss dword ptr [rsp],xmm1 fld dword ptr [rsp] fstp tbyte ptr [ecx] add rsp, 8 ret ?FromFloat@Real10@@QEAAXM@Z endp ;; public: void __cdecl Real10::FromInt64(__int64) ?FromInt64@Real10@@QEAAX_J@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] mov qword ptr [rsp],rdx fild qword ptr [rsp] fstp tbyte ptr [ecx] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?FromInt64@Real10@@QEAAX_J@Z endp ;; public: void __cdecl Real10::FromInt32(int) ?FromInt32@Real10@@QEAAXH@Z proc sub rsp, 8 mov dword ptr [rsp],edx fild dword ptr [rsp] fstp tbyte ptr [ecx] add rsp, 8 ret ?FromInt32@Real10@@QEAAXH@Z endp ;; public: void __cdecl Real10::FromUInt64(unsigned __int64) ?FromUInt64@Real10@@QEAAX_K@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] mov rax,1 shl 63 xor rdx, rax mov qword ptr [rsp],rdx fild qword ptr [rsp] mov qword ptr [rsp], rax fild qword ptr [rsp] ; -(1 << 63) fsubp ST(1),ST(0) fstp tbyte ptr [ecx] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?FromUInt64@Real10@@QEAAX_K@Z endp ;; public: double __cdecl Real10::ToDouble(void)const ?ToDouble@Real10@@QEBANXZ proc sub rsp, 8 fld tbyte ptr [rcx] fstp qword ptr [rsp] movsd xmm0, qword ptr [rsp] add rsp, 8 ret ?ToDouble@Real10@@QEBANXZ endp ;; public: float __cdecl Real10::ToFloat(void)const ?ToFloat@Real10@@QEBAMXZ proc sub rsp, 8 fld tbyte ptr [rcx] fstp dword ptr [rsp] movss xmm0, dword ptr [rsp] add rsp, 8 ret ?ToFloat@Real10@@QEBAMXZ endp ;; public: short __cdecl Real10::ToInt16(void)const ?ToInt16@Real10@@QEBAFXZ proc sub rsp, 8 fld tbyte ptr [rcx] fistp word ptr [rsp] mov ax, word ptr [rsp] add rsp, 8 ret ?ToInt16@Real10@@QEBAFXZ endp ;; public: int __cdecl Real10::ToInt32(void)const ?ToInt32@Real10@@QEBAHXZ proc sub rsp, 8 fld tbyte ptr [rcx] fistp dword ptr [rsp] mov eax, dword ptr [rsp] add rsp, 8 ret ?ToInt32@Real10@@QEBAHXZ endp ;; public: __int64 __cdecl Real10::ToInt64(void)const ?ToInt64@Real10@@QEBA_JXZ proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] fld tbyte ptr [rcx] fistp qword ptr [rsp] mov rax, qword ptr [rsp] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?ToInt64@Real10@@QEBA_JXZ endp ;; public: unsigned __int64 __cdecl Real10::ToUInt64(void)const ?ToUInt64@Real10@@QEBA_KXZ proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] mov rax,1 shl 63 mov qword ptr [rsp], rax fld tbyte ptr [rcx] fild qword ptr [rsp] faddp ST(1),ST(0) fistp qword ptr [rsp] xor rax, qword ptr [rsp] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?ToUInt64@Real10@@QEBA_KXZ endp ;; public: bool __cdecl Real10::FitsInDouble(void)const ?FitsInDouble@Real10@@QEBA_NXZ proc sub rsp, 8 fld tbyte ptr [ecx] fxam fnstsw ax mov dx, ax fstp qword ptr [rsp] fld qword ptr [rsp] fxam fnstsw word ptr ax fstp ST(0) xor ax, dx test ax, 4500h setz al add rsp, 8 ret ?FitsInDouble@Real10@@QEBA_NXZ endp ;; public: bool __cdecl Real10::FitsInFloat(void)const ?FitsInFloat@Real10@@QEBA_NXZ proc sub rsp, 8 fld tbyte ptr [ecx] fxam fnstsw ax mov dx, ax fstp dword ptr [rsp] fld dword ptr [rsp] fxam fnstsw word ptr ax fstp ST(0) xor ax, dx test ax, 4500h setz al add rsp, 8 ret ?FitsInFloat@Real10@@QEBA_NXZ endp ;; public: bool __cdecl Real10::IsZero(void)const ?IsZero@Real10@@QEBA_NXZ proc sub rsp, 8 fld tbyte ptr [ecx] ftst fnstsw word ptr [rsp] fstp ST(0) mov ax, 4000h xor ax, word ptr[rsp] test ax, 4500h setz al add rsp, 8 ret ?IsZero@Real10@@QEBA_NXZ endp ;; public: bool __cdecl Real10::IsNan(void)const ?IsNan@Real10@@QEBA_NXZ proc sub rsp, 8 fld tbyte ptr [ecx] fxam fnstsw word ptr [rsp] fstp ST(0) mov ax, 100h xor ax, word ptr[rsp] test ax, 4500h setz al add rsp, 8 ret ?IsNan@Real10@@QEBA_NXZ endp ;; public: static unsigned short __cdecl Real10::Compare(struct Real10 const &,struct Real10 const &) ?Compare@Real10@@SAGAEBU1@0@Z proc fld tbyte ptr [rdx] fld tbyte ptr [ecx] fcompp ; compare ST(0) with ST(1) then pop twice fnstsw ax ret ?Compare@Real10@@SAGAEBU1@0@Z endp ;; public: void __cdecl Real10::Add(struct Real10 const &,struct Real10 const &) ?Add@Real10@@QEAAXAEBU1@0@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] fld tbyte ptr [rdx] fld tbyte ptr [r8] faddp ST(1), ST(0) fstp tbyte ptr [rcx] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?Add@Real10@@QEAAXAEBU1@0@Z endp ;; public: void __cdecl Real10::Sub(struct Real10 const &,struct Real10 const &) ?Sub@Real10@@QEAAXAEBU1@0@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] fld tbyte ptr [rdx] fld tbyte ptr [r8] fsubp ST(1), ST(0) fstp tbyte ptr [rcx] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?Sub@Real10@@QEAAXAEBU1@0@Z endp ;; public: void __cdecl Real10::Mul(struct Real10 const &,struct Real10 const &) ?Mul@Real10@@QEAAXAEBU1@0@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] fld tbyte ptr [rdx] fld tbyte ptr [r8] fmulp ST(1), ST(0) fstp tbyte ptr [rcx] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?Mul@Real10@@QEAAXAEBU1@0@Z endp ;; public: void __cdecl Real10::Div(struct Real10 const &,struct Real10 const &) ?Div@Real10@@QEAAXAEBU1@0@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] fld tbyte ptr [rdx] fld tbyte ptr [r8] fdivp ST(1), ST(0) fstp tbyte ptr [rcx] fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ?Div@Real10@@QEAAXAEBU1@0@Z endp ;; public: void __cdecl Real10::Rem(struct Real10 const &,struct Real10 const &) ?Rem@Real10@@QEAAXAEBU1@0@Z proc sub rsp, 8+16 fnstcw word ptr [rsp+8] ; save cw fnstcw word ptr [rsp+10] or word ptr [rsp+10], 0300h ; set precision to double-extended fldcw word ptr [rsp+10] fld tbyte ptr [r8] fld tbyte ptr [rdx] Retry: fprem ; ST(0) := ST(0) % ST(1) doesn't pop! fnstsw ax sahf jp Retry fstp tbyte ptr [rcx] fstp ST(0) fldcw word ptr [rsp+8] ; restore cw add rsp, 8+16 ret ret ?Rem@Real10@@QEAAXAEBU1@0@Z endp ;; public: void __cdecl Real10::Negate(struct Real10 const &) ?Negate@Real10@@QEAAXAEBU1@@Z proc fld tbyte ptr [rdx] fchs fstp tbyte ptr [rcx] ret ?Negate@Real10@@QEAAXAEBU1@@Z endp ;; public: void __cdecl Real10::Abs(struct Real10 const &) ?Abs@Real10@@QEAAXAEBU1@@Z proc fld tbyte ptr [rdx] fabs fstp tbyte ptr [rcx] ret ?Abs@Real10@@QEAAXAEBU1@@Z endp end
;<ASCII To BCD> LDA ASCII SUI 030H MOV B,A LDA ASCII+1 SUI 030H RLC ;Rotate A left RLC ;Rotate A left RLC ;Rotate A left RLC ;Rotate A left ADD B STA BCD HLT BCD: db 000H ASCII: db 037H,039H
/* Copyright (c) 2002,2003, 2004 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst */ #include "boost/date_time/posix_time/posix_time.hpp" #include "../testfrmwk.hpp" #include "boost/date_time/filetime_functions.hpp" #include <cmath> #if defined(BOOST_HAS_FTIME) #include <windows.h> #endif int main() { #if defined(BOOST_HAS_FTIME) // skip tests if no FILETIME using namespace boost::posix_time; // adjustor is used to truncate ptime's fractional seconds for // comparison with SYSTEMTIME's milliseconds const int adjustor = time_duration::ticks_per_second() / 1000; for(int i = 0; i < 5; ++i){ FILETIME ft; SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st,&ft); ptime pt = from_ftime<ptime>(ft); check_equal("ptime year matches systemtime year", st.wYear, pt.date().year()); check_equal("ptime month matches systemtime month", st.wMonth, pt.date().month()); check_equal("ptime day matches systemtime day", st.wDay, pt.date().day()); check_equal("ptime hour matches systemtime hour", st.wHour, pt.time_of_day().hours()); check_equal("ptime minute matches systemtime minute", st.wMinute, pt.time_of_day().minutes()); check_equal("ptime second matches systemtime second", st.wSecond, pt.time_of_day().seconds()); check_equal("truncated ptime fractional second matches systemtime millisecond", st.wMilliseconds, (pt.time_of_day().fractional_seconds() / adjustor)); // burn up a little time for (int j=0; j<100000; j++) { SYSTEMTIME tmp; GetSystemTime(&tmp); } } // for loop // check that time_from_ftime works for pre-1970-Jan-01 dates, too // zero FILETIME should represent 1601-Jan-01 00:00:00.000 FILETIME big_bang_by_ms; big_bang_by_ms.dwLowDateTime = big_bang_by_ms.dwHighDateTime = 0; ptime pt = from_ftime<ptime>(big_bang_by_ms); check_equal("big bang ptime year matches 1601", 1601, pt.date().year()); check_equal("big bang ptime month matches Jan", 1, pt.date().month()); check_equal("big bang ptime day matches 1", 1, pt.date().day()); check_equal("big bang ptime hour matches 0", 0, pt.time_of_day().hours()); check_equal("big bang ptime minute matches 0", 0, pt.time_of_day().minutes()); check_equal("big bang ptime second matches 0", 0, pt.time_of_day().seconds()); check_equal("big bang truncated ptime fractional second matches 0", 0, (pt.time_of_day().fractional_seconds() / adjustor)); #else // BOOST_HAS_FTIME // we don't want a forced failure here, not a shortcoming check("FILETIME not available for this compiler/platform", true); #endif // BOOST_HAS_FTIME return printTestStats(); }
SPECIALCELEBIEVENT_CELEBI EQU $84 CelebiShrineEvent: call DelayFrame ld a, [wVramState] push af xor a ld [wVramState], a call LoadCelebiGFX depixel 0, 10, 7, 0 ld a, SPRITE_ANIM_INDEX_CELEBI call _InitSpriteAnimStruct ld hl, SPRITEANIMSTRUCT_TILE_ID add hl, bc ld [hl], SPECIALCELEBIEVENT_CELEBI ld hl, SPRITEANIMSTRUCT_ANIM_SEQ_ID add hl, bc ld [hl], SPRITE_ANIM_SEQ_CELEBI ld hl, SPRITEANIMSTRUCT_0F add hl, bc ld a, $80 ld [hl], a ld a, 160 ; frame count ld [wFrameCounter], a ld d, $0 .loop ld a, [wJumptableIndex] bit 7, a jr nz, .done push bc call GetCelebiSpriteTile inc d push de ld a, 36 * SPRITEOAMSTRUCT_LENGTH ld [wCurSpriteOAMAddr], a farcall DoNextFrameForAllSprites call CelebiEvent_CountDown ld c, 2 call DelayFrames pop de pop bc jr .loop .done pop af ld [wVramState], a call .RestorePlayerSprite_DespawnLeaves call CelebiEvent_SetBattleType ret .RestorePlayerSprite_DespawnLeaves: ld hl, wVirtualOAMSprite00TileID xor a ld c, 4 .OAMloop: ld [hli], a ; tile id rept SPRITEOAMSTRUCT_LENGTH + -1 inc hl endr inc a dec c jr nz, .OAMloop ld hl, wVirtualOAMSprite04 ld bc, wVirtualOAMEnd - wVirtualOAMSprite04 xor a call ByteFill ret LoadCelebiGFX: farcall ClearSpriteAnims ld de, SpecialCelebiLeafGFX ld hl, vTiles1 lb bc, BANK(SpecialCelebiLeafGFX), 4 call Request2bpp ld de, SpecialCelebiGFX ld hl, vTiles0 tile SPECIALCELEBIEVENT_CELEBI lb bc, BANK(SpecialCelebiGFX), 4 * 4 call Request2bpp xor a ld [wJumptableIndex], a ret CelebiEvent_CountDown: ld hl, wFrameCounter ld a, [hl] and a jr z, .done dec [hl] ret .done ld hl, wJumptableIndex set 7, [hl] ret CelebiEvent_SpawnLeaf: ; unused ld hl, wcf65 ld a, [hl] inc [hl] and $7 ret nz ld a, [hl] and $18 sla a add $40 ld d, a ld e, $0 ld a, SPRITE_ANIM_INDEX_FLY_LEAF ; fly land call _InitSpriteAnimStruct ld hl, SPRITEANIMSTRUCT_TILE_ID add hl, bc ld [hl], $80 ret SpecialCelebiLeafGFX: INCBIN "gfx/overworld/cut_grass.2bpp" SpecialCelebiGFX: INCBIN "gfx/overworld/celebi/1.2bpp" INCBIN "gfx/overworld/celebi/2.2bpp" INCBIN "gfx/overworld/celebi/3.2bpp" INCBIN "gfx/overworld/celebi/4.2bpp" UpdateCelebiPosition: ld hl, SPRITEANIMSTRUCT_XOFFSET add hl, bc ld a, [hl] push af ld hl, SPRITEANIMSTRUCT_YCOORD add hl, bc ld a, [hl] cp 8 * 10 + 2 jp nc, .FreezeCelebiPosition ld hl, SPRITEANIMSTRUCT_YCOORD add hl, bc inc [hl] ld hl, SPRITEANIMSTRUCT_0F add hl, bc ld a, [hl] ld d, a cp $3a jr c, .skip jr z, .skip sub $3 ld [hl], a .skip ld hl, SPRITEANIMSTRUCT_0E add hl, bc ld a, [hl] inc [hl] call CelebiEvent_Cosine ld hl, SPRITEANIMSTRUCT_XOFFSET add hl, bc ld [hl], a ld d, a ld hl, SPRITEANIMSTRUCT_XCOORD add hl, bc add [hl] cp 8 * 11 + 4 jr nc, .ShiftY cp 8 * 8 + 4 jr nc, .ReinitSpriteAnimFrame .ShiftY: pop af push af cp d jr nc, .moving_left ld hl, SPRITEANIMSTRUCT_XCOORD add hl, bc add [hl] cp 8 * 10 jr c, .float_up jr .float_down .moving_left ld hl, SPRITEANIMSTRUCT_XCOORD add hl, bc add [hl] cp 8 * 10 jr nc, .float_up .float_down ld hl, SPRITEANIMSTRUCT_YCOORD add hl, bc ld a, [hl] sub $2 ld [hl], a jr .ReinitSpriteAnimFrame .float_up ld hl, SPRITEANIMSTRUCT_YCOORD add hl, bc ld a, [hl] add $1 ld [hl], a .ReinitSpriteAnimFrame: pop af ld hl, SPRITEANIMSTRUCT_XCOORD add hl, bc add [hl] cp 8 * 10 jr c, .left cp -(8 * 3 + 2) jr nc, .left ld hl, SPRITEANIMSTRUCT_FRAMESET_ID add hl, bc ld a, SPRITE_ANIM_FRAMESET_CELEBI_RIGHT call ReinitSpriteAnimFrame jr .done .left ld hl, SPRITEANIMSTRUCT_FRAMESET_ID add hl, bc ld a, SPRITE_ANIM_FRAMESET_CELEBI_LEFT call ReinitSpriteAnimFrame .done ret .FreezeCelebiPosition: pop af ld hl, SPRITEANIMSTRUCT_FRAMESET_ID add hl, bc ld a, SPRITE_ANIM_FRAMESET_CELEBI_LEFT call ReinitSpriteAnimFrame ret CelebiEvent_Cosine: ; a = d * cos(a * pi/32) add %010000 ; cos(x) = sin(x + pi/2) calc_sine_wave GetCelebiSpriteTile: push hl push bc push de ld a, d ld d, $3 ld e, d cp $0 jr z, .Frame1 cp d jr z, .Frame2 call .AddE cp d jr z, .Frame3 call .AddE cp d jr z, .Frame4 call .AddE cp d jr c, .done jr .restart .Frame1: ld a, SPECIALCELEBIEVENT_CELEBI jr .load_tile .Frame2: ld a, SPECIALCELEBIEVENT_CELEBI + 4 jr .load_tile .Frame3: ld a, SPECIALCELEBIEVENT_CELEBI + 8 jr .load_tile .Frame4: ld a, SPECIALCELEBIEVENT_CELEBI + 12 .load_tile ld hl, SPRITEANIMSTRUCT_TILE_ID add hl, bc ld [hl], a jr .done .restart pop de ld d, $ff push de .done pop de pop bc pop hl ret .AddE: push af ld a, d add e ld d, a pop af ret CelebiEvent_SetBattleType: ld a, BATTLETYPE_CELEBI ld [wBattleType], a ret CheckCaughtCelebi: ld a, [wBattleResult] bit BATTLERESULT_CAUGHT_CELEBI, a jr z, .false ld a, TRUE ld [wScriptVar], a jr .done .false xor a ; FALSE ld [wScriptVar], a .done ret
; ; $Id: 0x27.asm,v 1.1.1.1 2016/03/27 08:40:13 raptor Exp $ ; ; 0x27 explanation - from xchg rax,rax by xorpd@xorpd.net ; Copyright (c) 2016 Marco Ivaldi <raptor@0xdeadbeef.info> ; ; This snippet performs the following operation: ; ; rax = rax>>((cl>>1) + ((cl + 1)>>1)) ; ; It calculates the result of the Euclidean (integer) ; division of the value in rax by the following values, ; depending on the initial value stored in the cl ; register: ; ; 0 >>0 2^0 = 1 ; 1 >>1 2^1 = 2 ; 2 >>1+2=3 2^3 = 8 ; 3 >>1+2+3=6 2^6 = 64 ; 4 >>1+2+3+4=10 2^10 = 1024 ; 5 >>1+2+3+4+5=15 2^15 = 32768 ; 6 >>1+2+3+4+5+6=21 2^21 = 2097152 ; 7 >>1+2+3+4+5+6+7=28 2^28 = 268435456 ; 8 >>1+2+3+4+5+6+7+8=36 2^36 = 68719476736 ; [...] ; ; For instance, if rax = 0xffffffff and cl = 5, the output ; of the snippet will be (int)(0xffffffff / pow(2, 15)) = ; = (int)(4294967295 / 32768) = (int)131071.99 = 131071 = ; = 0x1ffff. ; ; See also: ; https://en.wikipedia.org/wiki/Triangular_number ; https://oeis.org/A006125 ; ; I wrote a short C program to simplify the analysis: ; ; #include <stdio.h> ; #include <stdint.h> ; main() ; { ; unsigned char cl; ; int64_t rax = 0xffffffff; ; int i; ; for (i = 0; i < 256; i++) { ; cl = i; ; printf("cl:\t%u\t\t", cl); ; rax = rax>>((cl>>1) + ((cl + 1)>>1)); ; printf("rax:\t0x%llx\n", rax); ; } ; } ; ; Example run: ; $ ./0x27_helper ; cl: 0 rax: 0xffffffff ; cl: 1 rax: 0x7fffffff ; cl: 2 rax: 0x1fffffff ; cl: 3 rax: 0x3ffffff ; cl: 4 rax: 0x3fffff ; cl: 5 rax: 0x1ffff ; cl: 6 rax: 0x7ff ; cl: 7 rax: 0xf ; cl: 8 rax: 0x0 ; [...] ; ; This analysis was facilitated by the assembly REPL rappel ; by yrp604@yahoo.com: ; ; https://github.com/yrp604/rappel/ ; BITS 64 SECTION .text global main main: mov ch,cl ; inc ch ; ch = cl + 1 shr ch,1 ; ch = ch>>1 shr cl,1 ; cl = cl>>1 shr rax,cl ; rax = rax>>cl xchg ch,cl ; shr rax,cl ; rax = rax>>ch ; i.e. rax = rax>>((cl>>1) + ((cl + 1)>>1))
; A107820: a(1)=3, a(2)=5; thereafter a(n) = n+5. ; 3,5,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76 mov $1,$0 pow $1,2 min $1,3 add $0,$1 add $0,3
mov r0,#-1 mov r1,#1 mov r2,#-2 mov r3,#-3 mov r4,#-4 mov r5,#-5 mov r6,#-6 mov r7,#-7 mov r8,#-8 mov r9,#-9 halt
; A275630: a(n) = product of distinct primes dividing prime(n)^2 - 1. ; Submitted by Christian Krause ; 3,2,6,6,30,42,6,30,66,210,30,114,210,462,138,78,870,930,1122,210,222,390,1722,330,42,510,1326,318,330,798,42,4290,2346,4830,1110,570,6162,246,3486,7482,2670,2730,570,582,462,330,11130,1554,12882,13110,2262,3570,330,210,258,8646,2010,510,19182,9870,20022,3066,7854,12090,12246,25122,27390,546,30102,6090,3894,5370,8418,34782,3990,1146,37830,13134,2010,20910,43890,44310,1290,1302,24090,49062,210,26106,53130,13398,18174,7170,366,8610,2490,10542,64770,11310,22794,8130 seq $0,40 ; The prime numbers. pow $0,2 sub $0,2 seq $0,7947 ; Largest squarefree number dividing n: the squarefree kernel of n, rad(n), radical of n.
CPU 686 BITS 32 %define DATA_REG 0x60 %define EOI 0x20 %define PIC1_CMD 0x20 %define PIC2_CMD 0xA0 global _mouse_isr global _mouse_byte1 global _mouse_byte2 global _mouse_byte3 global _pack_completo section .data _mouse_byte1 dd 0 _mouse_byte2 dd 0 _mouse_byte3 dd 0 _pack_completo dd 0 next_byte dd 1 section .text _mouse_isr: push eax push ecx xor eax, eax in al, DATA_REG mov ecx, dword[next_byte] cmp ecx, 3 je byte3 cmp ecx, 2 je byte2 byte1: mov dword[_mouse_byte1], eax mov dword[_pack_completo], 0 mov ecx, 2 jmp fim byte2: mov dword[_mouse_byte2], eax mov dword[_pack_completo], 0 mov ecx, 3 jmp fim byte3: mov dword[_mouse_byte3], eax mov dword[_pack_completo], 1 mov ecx, 1 fim: mov dword[next_byte], ecx mov al, EOI out PIC1_CMD, al out PIC2_CMD, al pop ecx pop eax iretd END
/*++ Copyright (c) 1998-1999 Microsoft Corporation Module Name: csd.cxx Abstract: This is from the ATL sources. This provides a simple interface for managing ACLs and SDs Environment: User mode Revision History: 04/06/97 -srinivac- Created it from ATL sources 08/07/98 -eyals- Stole from \nt\private\dirsync\dsserver\server, modified & renamed --*/ // // These routines are all non-unicode // // #ifdef UNICODE // Jeff W: Making these routines unicode again!! // #undef UNICODE // #endif #ifdef __cplusplus extern "C" { #endif // include // #include <nt.h> #include <ntrtl.h> #include <nturtl.h> #ifdef __cplusplus } #endif #include <windows.h> #include <ntseapi.h> #include <sddl.h> #if 0 #include <stdio.h> #define DBGOUT(x) (OutputDebugString(x)) #define DBGOUT_SID(psid, cbsid) \ { \ CHAR buf[1024]; \ DWORD j = (cbsid) / sizeof(DWORD); \ sprintf(buf, "sid<%lu> [", j); \ DBGOUT(buf); \ for (DWORD i=0; i<j;i++) \ { \ sprintf(buf, "%X%c", *((PDWORD)(psid)+i), \ j == i+1 ? ']' : '.'); \ DBGOUT(buf); \ } \ } #else #define DBGOUT(x) #define DBGOUT_SID(x, cbsid); #endif #include "csd.h" CSecurityDescriptor::CSecurityDescriptor() { m_pSD = NULL; m_pOwner = NULL; m_pGroup = NULL; m_pDACL = NULL; m_pSACL= NULL; } CSecurityDescriptor::~CSecurityDescriptor() { if ( m_pSD ) delete [] m_pSD; if ( m_pOwner ) delete [] m_pOwner, m_pOwner = NULL; if ( m_pGroup ) delete [] m_pGroup, m_pGroup = NULL; if ( m_pDACL ) delete [] m_pDACL, m_pDACL = NULL; if ( m_pSACL ) delete [] m_pSACL, m_pSACL = NULL; } HRESULT CSecurityDescriptor::Initialize() { if ( m_pSD ) { delete [] m_pSD; m_pSD = NULL; } if (m_pOwner) { delete [] m_pOwner; m_pOwner = NULL; } if (m_pGroup) { delete [] m_pGroup; m_pGroup = NULL; } if (m_pDACL) { delete [] m_pDACL; m_pDACL = NULL; } if (m_pSACL) { delete [] m_pSACL; m_pSACL = NULL; } m_pSD = new BYTE[ sizeof( SECURITY_DESCRIPTOR ) ]; if (!m_pSD) return E_OUTOFMEMORY; if (!InitializeSecurityDescriptor(m_pSD, SECURITY_DESCRIPTOR_REVISION)) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); delete [] m_pSD; m_pSD = NULL; return hr; } // DEVNOTE: commented out. You wanna prevent all from touching this by default // Set the DACL to allow EVERYONE // SetSecurityDescriptorDacl(m_pSD, TRUE, NULL, FALSE); return S_OK; } HRESULT CSecurityDescriptor::InitializeFromProcessToken(BOOL bDefaulted) { PSID pUserSid; PSID pGroupSid; HRESULT hr=S_OK; Initialize(); hr = GetProcessSids(&pUserSid, &pGroupSid); if ( FAILED( hr ) ) goto cleanup; hr = SetOwner(pUserSid, bDefaulted); if ( FAILED( hr ) ) goto cleanup; hr = SetGroup(pGroupSid, bDefaulted); if ( FAILED( hr ) ) goto cleanup; cleanup: if ( pUserSid ) delete [] pUserSid; if ( pGroupSid ) delete [] pGroupSid; return hr; } HRESULT CSecurityDescriptor::InitializeFromThreadToken(BOOL bDefaulted, BOOL bRevertToProcessToken) { PSID pUserSid; PSID pGroupSid; HRESULT hr=S_OK; Initialize(); hr = GetThreadSids(&pUserSid, &pGroupSid); if (HRESULT_CODE(hr) == ERROR_NO_TOKEN && bRevertToProcessToken) hr = GetProcessSids(&pUserSid, &pGroupSid); if ( FAILED( hr ) ) goto cleanup; hr = SetOwner(pUserSid, bDefaulted); if ( FAILED( hr ) ) goto cleanup; hr = SetGroup(pGroupSid, bDefaulted); if ( FAILED( hr ) ) goto cleanup; cleanup: if ( pUserSid ) delete [] pUserSid; if ( pGroupSid ) delete [] pGroupSid; return hr; } HRESULT CSecurityDescriptor::SetOwner(PSID pOwnerSid, BOOL bDefaulted) { // Mark the SD as having no owner if ( !SetSecurityDescriptorOwner( m_pSD, NULL, bDefaulted ) ) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); return hr; } if ( m_pOwner ) { delete [] m_pOwner; m_pOwner = NULL; } // If they asked for no owner don't do the copy if ( pOwnerSid == NULL ) return S_OK; // Make a copy of the Sid for the return value DWORD dwSize = GetLengthSid(pOwnerSid); m_pOwner = ( PSID ) new BYTE[ dwSize ]; if (!m_pOwner) { // Insufficient memory to allocate Sid return E_OUTOFMEMORY; } if (!CopySid(dwSize, m_pOwner, pOwnerSid)) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); delete [] m_pOwner; m_pOwner = NULL; return hr; } if (!SetSecurityDescriptorOwner(m_pSD, m_pOwner, bDefaulted)) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); delete [] m_pOwner; m_pOwner = NULL; return hr; } return S_OK; } HRESULT CSecurityDescriptor::SetGroup(PSID pGroupSid, BOOL bDefaulted) { // Mark the SD as having no Group if (!SetSecurityDescriptorGroup(m_pSD, NULL, bDefaulted)) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); return hr; } if (m_pGroup) { delete [] m_pGroup; m_pGroup = NULL; } // If they asked for no Group don't do the copy if (pGroupSid == NULL) return S_OK; // Make a copy of the Sid for the return value DWORD dwSize = GetLengthSid(pGroupSid); m_pGroup = ( PSID ) new BYTE[ dwSize ]; if (!m_pGroup) { // Insufficient memory to allocate Sid return E_OUTOFMEMORY; } if (!CopySid(dwSize, m_pGroup, pGroupSid)) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); delete [] m_pGroup; m_pGroup = NULL; return hr; } if (!SetSecurityDescriptorGroup(m_pSD, m_pGroup, bDefaulted)) { HRESULT hr = HRESULT_FROM_WIN32( GetLastError() ); delete [] m_pGroup; m_pGroup = NULL; return hr; } return S_OK; } HRESULT CSecurityDescriptor::Allow( LPCTSTR pszPrincipal, DWORD dwAccessMask, DWORD AceFlags ) { HRESULT hr = AddAccessAllowedACEToACL( &m_pDACL, pszPrincipal, dwAccessMask, AceFlags ); if ( SUCCEEDED( hr ) ) SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE); return hr; } HRESULT CSecurityDescriptor::Deny( LPCTSTR pszPrincipal, DWORD dwAccessMask ) { HRESULT hr = AddAccessDeniedACEToACL( &m_pDACL, pszPrincipal, dwAccessMask ); if ( SUCCEEDED( hr ) ) SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE); return hr; } HRESULT CSecurityDescriptor::Revoke(LPCTSTR pszPrincipal) { HRESULT hr = S_OK; int retries = 250; // // There can be duplicate ACLs with the same principle. Keep whacking // ACEs until they're all gone or we hit a hard retry limit. // while ( hr == S_OK && --retries > 0 ) { hr = RemovePrincipalFromACL( m_pDACL, pszPrincipal ); if ( SUCCEEDED( hr ) ) { SetSecurityDescriptorDacl( m_pSD, TRUE, m_pDACL, FALSE ); } } return hr; } HRESULT CSecurityDescriptor::Allow(PSID pPrincipal, DWORD dwAccessMask, DWORD AceFlags) { HRESULT hr = AddAccessAllowedACEToACL(&m_pDACL, pPrincipal, dwAccessMask, AceFlags); if ( SUCCEEDED( hr ) ) SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE); return hr; } HRESULT CSecurityDescriptor::Deny(PSID pPrincipal, DWORD dwAccessMask) { HRESULT hr = AddAccessDeniedACEToACL(&m_pDACL, pPrincipal, dwAccessMask); if ( SUCCEEDED( hr ) ) SetSecurityDescriptorDacl(m_pSD, TRUE, m_pDACL, FALSE); return hr; } HRESULT CSecurityDescriptor::Revoke(PSID pPrincipal) { HRESULT hr = S_OK; int retries = 250; // // There can be duplicate ACLs with the same principle. Keep whacking // ACEs until they're all gone or we hit a hard retry limit. // while ( hr == S_OK && --retries > 0 ) { hr = RemovePrincipalFromACL( m_pDACL, pPrincipal ); if ( SUCCEEDED( hr ) ) { SetSecurityDescriptorDacl( m_pSD, TRUE, m_pDACL, FALSE ); } } return hr; } HRESULT CSecurityDescriptor::GetProcessSids(PSID* ppUserSid, PSID* ppGroupSid) { BOOL bRes; HRESULT hr; HANDLE hToken = NULL; if (ppUserSid) *ppUserSid = NULL; if (ppGroupSid) *ppGroupSid = NULL; bRes = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken); if (!bRes) { // Couldn't open process token hr = HRESULT_FROM_WIN32( GetLastError() ); return hr; } hr = GetTokenSids(hToken, ppUserSid, ppGroupSid); // // clean all memory temp. allocations // if(hToken) CloseHandle(hToken); return hr; } HRESULT CSecurityDescriptor::GetThreadSids(PSID* ppUserSid, PSID* ppGroupSid, BOOL bOpenAsSelf) { BOOL bRes; HRESULT hr; HANDLE hToken = NULL; if (ppUserSid) *ppUserSid = NULL; if (ppGroupSid) *ppGroupSid = NULL; bRes = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, bOpenAsSelf, &hToken); if (!bRes) { // Couldn't open thread token hr = HRESULT_FROM_WIN32( GetLastError() ); return hr; } hr = GetTokenSids(hToken, ppUserSid, ppGroupSid); // // clean all memory temp. allocations // if(hToken) CloseHandle(hToken); return hr; } HRESULT CSecurityDescriptor::GetTokenSids(HANDLE hToken, PSID* ppUserSid, PSID* ppGroupSid) { DWORD dwSize; HRESULT hr; PTOKEN_USER ptkUser = NULL; PTOKEN_PRIMARY_GROUP ptkGroup = NULL; PSID pSid = NULL; if (ppUserSid) *ppUserSid = NULL; if (ppGroupSid) *ppGroupSid = NULL; if (ppUserSid) { // Get length required for TokenUser by specifying buffer length of 0 GetTokenInformation(hToken, TokenUser, NULL, 0, &dwSize); hr = GetLastError(); if (hr != ERROR_INSUFFICIENT_BUFFER) { // Expected ERROR_INSUFFICIENT_BUFFER hr = HRESULT_FROM_WIN32(hr); goto failed; } ptkUser = ( TOKEN_USER * ) new BYTE[ dwSize ]; if (!ptkUser) { // Insufficient memory to allocate TOKEN_USER hr = E_OUTOFMEMORY; goto failed; } // Get Sid of process token. if (!GetTokenInformation(hToken, TokenUser, ptkUser, dwSize, &dwSize)) { // Couldn't get user info hr = HRESULT_FROM_WIN32( GetLastError() ); goto failed; } // Make a copy of the Sid for the return value dwSize = GetLengthSid(ptkUser->User.Sid); pSid = ( PSID ) new BYTE[ dwSize ]; if ( !pSid ) { // Insufficient memory to allocate Sid hr = E_OUTOFMEMORY; goto failed; } if (!CopySid(dwSize, pSid, ptkUser->User.Sid)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto failed; } *ppUserSid = pSid; pSid = NULL; delete [] ptkUser; ptkUser = NULL; } if (ppGroupSid) { // Get length required for TokenPrimaryGroup by specifying buffer length of 0 GetTokenInformation(hToken, TokenPrimaryGroup, NULL, 0, &dwSize); hr = GetLastError(); if (hr != ERROR_INSUFFICIENT_BUFFER) { // Expected ERROR_INSUFFICIENT_BUFFER hr = HRESULT_FROM_WIN32(hr); goto failed; } ptkGroup = ( TOKEN_PRIMARY_GROUP * ) new BYTE[ dwSize ]; if (!ptkGroup) { // Insufficient memory to allocate TOKEN_USER hr = E_OUTOFMEMORY; goto failed; } // Get Sid of process token. if (!GetTokenInformation(hToken, TokenPrimaryGroup, ptkGroup, dwSize, &dwSize)) { // Couldn't get user info hr = HRESULT_FROM_WIN32( GetLastError() ); goto failed; } // Make a copy of the Sid for the return value dwSize = GetLengthSid(ptkGroup->PrimaryGroup); pSid = ( PSID ) new BYTE[ dwSize ]; if ( !pSid ) { // Insufficient memory to allocate Sid hr = E_OUTOFMEMORY; goto failed; } if (!CopySid(dwSize, pSid, ptkGroup->PrimaryGroup)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto failed; } *ppGroupSid = pSid; pSid = NULL; delete [] ptkGroup; } return S_OK; failed: if ( ptkUser ) delete [] ptkUser; if ( ptkGroup ) delete [] ptkGroup; if ( pSid ) delete [] pSid; return hr; } HRESULT CSecurityDescriptor::IsSidInTokenGroups(HANDLE hToken, PSID pSid, PBOOL pbMember) { DWORD dwSize; HRESULT hr = S_OK; PTOKEN_GROUPS ptkGroups = NULL; ULONG i; BOOL bMember = FALSE; if (!pbMember) { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } // Get length required for TokenUser by specifying buffer length of 0 GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize); hr = GetLastError(); if (hr != ERROR_INSUFFICIENT_BUFFER) { // Expected ERROR_INSUFFICIENT_BUFFER hr = HRESULT_FROM_WIN32(hr); goto failed; } hr = ERROR_SUCCESS; ptkGroups = ( TOKEN_GROUPS * ) new BYTE[ dwSize ]; if (!ptkGroups) { // Insufficient memory to allocate TOKEN_USER hr = E_OUTOFMEMORY; goto failed; } // Get Sid of process token. if (!GetTokenInformation(hToken, TokenGroups, ptkGroups, dwSize, &dwSize)) { // Couldn't get groups info hr = HRESULT_FROM_WIN32( GetLastError() ); goto failed; } #if 0 // // print user sid // { PSID pUSid=NULL; if (ERROR_SUCCESS == GetCurrentUserSID(&pUSid, TRUE)) { DBGOUT("User Sid:"); DBGOUT_SID(pUSid, GetLengthSid(pSid)); DBGOUT("\n"); delete [] pUSid; } } #endif DBGOUT("searching for "); DBGOUT_SID(pSid, GetLengthSid(pSid)); DBGOUT(" ...\n"); for (i=0; i<ptkGroups->GroupCount; i++) { DBGOUT(" >"); DBGOUT_SID(ptkGroups->Groups[i].Sid, GetLengthSid(ptkGroups->Groups[i].Sid)); DBGOUT(" ?\n"); if (TRUE == (bMember = RtlEqualSid(pSid, ptkGroups->Groups[i].Sid))) { DBGOUT(" >> EqualSid\n"); break; } } *pbMember = bMember; failed: if ( ptkGroups ) delete [] ptkGroups; return hr; } HRESULT CSecurityDescriptor::GetCurrentUserSID(PSID *ppSid, BOOL bThread) { HANDLE tkHandle = NULL; BOOL bstatus=FALSE; if ( bThread ) { bstatus = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &tkHandle); } else { bstatus = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tkHandle); } if ( bstatus ) { TOKEN_USER *tkUser; DWORD tkSize = 0; DWORD sidLength; // Call to get size information for alloc GetTokenInformation(tkHandle, TokenUser, NULL, 0, &tkSize); tkUser = ( TOKEN_USER * ) new BYTE[ tkSize ]; if (!tkUser) { SetLastError( E_OUTOFMEMORY ); goto Failed; } // Now make the real call if (GetTokenInformation(tkHandle, TokenUser, tkUser, tkSize, &tkSize)) { sidLength = GetLengthSid(tkUser->User.Sid); *ppSid = ( PSID ) new BYTE[ sidLength ]; if ( !*ppSid ) { // DEVNOTE: this isn't consistent with HRESULT either // better to just have a single failure return CloseHandle(tkHandle); return E_OUTOFMEMORY; } memcpy(*ppSid, tkUser->User.Sid, sidLength); CloseHandle(tkHandle); delete [] tkUser; return S_OK; } else { CloseHandle(tkHandle); delete [] tkUser; return HRESULT_FROM_WIN32( GetLastError() ); } } Failed: // // clean all memory temp. allocations // if( tkHandle ) CloseHandle( tkHandle ); return HRESULT_FROM_WIN32( GetLastError() ); } HRESULT CSecurityDescriptor::GetPrincipalSID(LPCTSTR pszPrincipal, PSID *ppSid) { HRESULT hr; LPTSTR pszRefDomain = NULL; DWORD dwDomainSize = 0; DWORD dwSidSize = 0; SID_NAME_USE snu; // Call to get size info for alloc LookupAccountName( NULL, pszPrincipal, *ppSid, &dwSidSize, pszRefDomain, &dwDomainSize, &snu ); hr = GetLastError(); if ( hr != ERROR_INSUFFICIENT_BUFFER ) { return HRESULT_FROM_WIN32( hr ); } pszRefDomain = new TCHAR[ dwDomainSize ]; if ( pszRefDomain == NULL ) { return E_OUTOFMEMORY; } *ppSid = ( PSID ) new BYTE[ dwSidSize ]; if (*ppSid != NULL) { if ( !LookupAccountName( NULL, pszPrincipal, *ppSid, &dwSidSize, pszRefDomain, &dwDomainSize, &snu )) { delete [] *ppSid; *ppSid = NULL; delete [] pszRefDomain; return HRESULT_FROM_WIN32( GetLastError() ); } delete [] pszRefDomain; return S_OK; } delete [] pszRefDomain; return E_OUTOFMEMORY; } HRESULT CSecurityDescriptor::Attach( PSECURITY_DESCRIPTOR pSelfRelativeSD, BYTE AclRevision, BOOL bAllowInheritance ) { PACL pDACL = NULL; PACL pSACL = NULL; BOOL bDACLPresent, bSACLPresent; BOOL bDefaulted; BOOL bStatus = FALSE; ACCESS_ALLOWED_ACE* pACE; HRESULT hr; PSID pUserSid; PSID pGroupSid; SetLastError( ERROR_SUCCESS ); if ( !pSelfRelativeSD ) { return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = Initialize(); if ( FAILED( hr ) ) { return hr; } // get the existing DACL. if ( !GetSecurityDescriptorDacl( pSelfRelativeSD, &bDACLPresent, &pDACL, &bDefaulted ) || !pDACL) { goto failed; } if ( bDACLPresent ) { AclRevision = pDACL->AclRevision; if (pDACL) { m_pDACL = ( PACL ) new BYTE[ pDACL->AclSize ]; if (!m_pDACL) goto failed; // initialize the DACL if (!InitializeAcl(m_pDACL, pDACL->AclSize, AclRevision)) goto failed; // copy the ACES for ( int i = 0; i < pDACL->AceCount; i++ ) { if ( !GetAce(pDACL, i, (void **)&pACE) ) { goto failed; } pUserSid = ExtractAceSid( pACE ); if ( pUserSid ) { if ( AclRevision < ACL_REVISION_DS ) { if ( pACE->Header.AceType == ACCESS_ALLOWED_ACE_TYPE ) { bStatus = AddAccessAllowedAce( m_pDACL, AclRevision, pACE->Mask, pUserSid ); } else if ( pACE->Header.AceType == ACCESS_DENIED_ACE_TYPE ) { bStatus = AddAccessDeniedAce( m_pDACL, AclRevision, pACE->Mask, pUserSid ); } else { bStatus = TRUE; } } else { if ( bAllowInheritance || !(pACE->Header.AceFlags & INHERITED_ACE) ) { // // For DS ACEs we need to optionaly skip inheritable ones // if ( pACE->Header.AceType == ACCESS_ALLOWED_ACE_TYPE ) { bStatus = AddAccessAllowedAce( m_pDACL, AclRevision, pACE->Mask, pUserSid ); } else if ( pACE->Header.AceType == ACCESS_DENIED_ACE_TYPE ) { bStatus = AddAccessDeniedAce( m_pDACL, AclRevision, pACE->Mask, pUserSid ); } else { bStatus = TRUE; } } else { // don't fail bStatus = TRUE; } } if ( !bStatus ) { goto failed; } } else { // // unknown ace // SetLastError( ERROR_INVALID_ACL ); goto failed; } } if ( !IsValidAcl( m_pDACL ) ) { goto failed; } } // set the DACL if ( !SetSecurityDescriptorDacl( m_pSD, m_pDACL ? TRUE : FALSE, m_pDACL, bDefaulted ) ) { goto failed; } } // get the existing SACL. if ( !GetSecurityDescriptorSacl( pSelfRelativeSD, &bSACLPresent, &pSACL, &bDefaulted ) ) { goto failed; } if ( bSACLPresent ) { ASSERT( !"DNS SERVER SHOULD NOT DEAL WITH SACLS!!!" ); goto failed; #if 0 AclRevision = pSACL->AclRevision; if ( pSACL ) { m_pSACL = ( PACL ) new BYTE[ pSACL->AclSize ]; if ( !m_pSACL ) { goto failed; } if ( !InitializeAcl( m_pSACL, pSACL->AclSize, ACL_REVISION ) ) { goto failed; } if ( !CopyACL( m_pSACL, pSACL ) ) { goto failed; } if ( !IsValidAcl( m_pSACL ) ) { goto failed; } } // set the SACL if ( !SetSecurityDescriptorSacl( m_pSD, m_pSACL ? TRUE : FALSE, m_pSACL, bDefaulted ) ) { goto failed; } #endif } if (!GetSecurityDescriptorOwner(m_pSD, &pUserSid, &bDefaulted)) goto failed; if (FAILED(SetOwner(pUserSid, bDefaulted))) goto failed; if (!GetSecurityDescriptorGroup(m_pSD, &pGroupSid, &bDefaulted)) goto failed; if (FAILED(SetGroup(pGroupSid, bDefaulted))) goto failed; if (!IsValidSecurityDescriptor(m_pSD)) goto failed; return hr; failed: if ( m_pDACL ) delete [] m_pDACL, m_pDACL = NULL; if ( m_pSD ) delete [] m_pSD, m_pSD = NULL; hr = HRESULT_FROM_WIN32( GetLastError() ); return FAILED( hr ) ? hr : E_UNEXPECTED; } HRESULT CSecurityDescriptor::Attach(LPCTSTR pszSdString) { BOOL bStatus = TRUE; HRESULT hrStatus = NOERROR; PSECURITY_DESCRIPTOR pSd=NULL; // // Get SD in self-relative form // bStatus = ConvertStringSecurityDescriptorToSecurityDescriptor(pszSdString, SDDL_REVISION, &pSd, NULL ); hrStatus = bStatus ? Attach(pSd) : HRESULT_FROM_WIN32( GetLastError() ); if( pSd ) LocalFree( pSd ); return hrStatus; } #if 0 HRESULT CSecurityDescriptor::AttachObject(HANDLE hObject) { HRESULT hr; DWORD dwSize = 0; PSECURITY_DESCRIPTOR pSD = NULL; GetKernelObjectSecurity(hObject, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, pSD, 0, &dwSize); hr = GetLastError(); if (hr != ERROR_INSUFFICIENT_BUFFER) return HRESULT_FROM_WIN32(hr); pSD = (PSECURITY_DESCRIPTOR) new BYTE[ dwSize ]; if (!GetKernelObjectSecurity(hObject, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, pSD, dwSize, &dwSize)) { hr = HRESULT_FROM_WIN32( GetLastError() ); delete [] pSD; return hr; } hr = Attach(pSD); delete [] pSD; return hr; } #endif HRESULT CSecurityDescriptor::CopyACL(PACL pDest, PACL pSrc) { ACL_SIZE_INFORMATION aclSizeInfo; LPVOID pAce; ACE_HEADER *aceHeader; if (pSrc == NULL) return S_OK; if (!GetAclInformation(pSrc, (LPVOID) &aclSizeInfo, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation)) return HRESULT_FROM_WIN32( GetLastError() ); // Copy all of the ACEs to the new ACL for (UINT i = 0; i < aclSizeInfo.AceCount; i++) { if (!GetAce(pSrc, i, &pAce)) return HRESULT_FROM_WIN32( GetLastError() ); aceHeader = (ACE_HEADER *) pAce; if (!AddAce(pDest, ACL_REVISION, 0xffffffff, pAce, aceHeader->AceSize)) return HRESULT_FROM_WIN32( GetLastError() ); } return S_OK; } HRESULT CSecurityDescriptor::AddAccessDeniedACEToACL(PACL *ppAcl, LPCTSTR pszPrincipal, DWORD dwAccessMask) { DWORD returnValue; PSID principalSID = NULL; // PREFIX BUG: Reworked this so we have one return path and not leaking SID. returnValue = GetPrincipalSID(pszPrincipal, &principalSID); if ( !FAILED( returnValue ) ) { returnValue = AddAccessDeniedACEToACL( ppAcl, principalSID, dwAccessMask ); } delete [] principalSID; return FAILED( returnValue )? returnValue : S_OK; } HRESULT CSecurityDescriptor::AddAccessDeniedACEToACL(PACL *ppAcl, PSID principalSID, DWORD dwAccessMask) { ACL_SIZE_INFORMATION aclSizeInfo; int aclSize; DWORD returnValue; PACL oldACL; PACL newACL = NULL; HRESULT status = S_OK; oldACL = *ppAcl; aclSizeInfo.AclBytesInUse = 0; if (*ppAcl != NULL) { GetAclInformation(oldACL, (LPVOID) &aclSizeInfo, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation); } aclSize = aclSizeInfo.AclBytesInUse + sizeof(ACL) + sizeof(ACCESS_DENIED_ACE) + GetLengthSid(principalSID) - sizeof(DWORD); newACL = ( PACL ) new BYTE[ aclSize ]; if ( !newACL ) { status = E_OUTOFMEMORY; goto Failed; } if (!InitializeAcl(newACL, aclSize, ACL_REVISION)) { status = HRESULT_FROM_WIN32( GetLastError() ); goto Failed; } if (!AddAccessDeniedAce(newACL, ACL_REVISION2, dwAccessMask, principalSID)) { status = HRESULT_FROM_WIN32( GetLastError() ); goto Failed; } status = CopyACL( newACL, oldACL ); if ( FAILED( status ) ) { goto Failed; } *ppAcl = newACL; newACL = NULL; delete [] oldACL; return S_OK; Failed: delete [] newACL; return status; } HRESULT CSecurityDescriptor::AddAccessAllowedACEToACL(PACL *ppAcl, LPCTSTR pszPrincipal, DWORD dwAccessMask, DWORD AceFlags) { DWORD returnValue; PSID principalSID = NULL; returnValue = GetPrincipalSID(pszPrincipal, &principalSID ); if ( FAILED( returnValue ) ) { return returnValue; } returnValue = AddAccessAllowedACEToACL(ppAcl, principalSID, dwAccessMask, AceFlags); delete [] principalSID; return FAILED( returnValue ) ? returnValue : S_OK; } HRESULT CSecurityDescriptor::AddAccessAllowedACEToACL(PACL *ppAcl, PSID principalSID, DWORD dwAccessMask, DWORD AceFlags) { ACL_SIZE_INFORMATION aclSizeInfo; int aclSize; DWORD returnValue; PACL oldACL; PACL newACL = NULL; HRESULT hres = 0; if ( !principalSID ) { hres = E_INVALIDARG; goto Failed; } oldACL = *ppAcl; aclSizeInfo.AclBytesInUse = 0; if ( *ppAcl != NULL ) { GetAclInformation( oldACL, (LPVOID) &aclSizeInfo, (DWORD) sizeof(ACL_SIZE_INFORMATION), AclSizeInformation); } aclSize = aclSizeInfo.AclBytesInUse + sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(principalSID) - sizeof(DWORD); newACL = (PACL) new BYTE[ aclSize ]; if ( !newACL ) { hres = E_OUTOFMEMORY; goto Failed; } if ( !InitializeAcl( newACL, aclSize, ACL_REVISION ) ) { hres = HRESULT_FROM_WIN32( GetLastError() ); goto Failed; } returnValue = CopyACL( newACL, oldACL ); if ( FAILED( returnValue ) ) { hres = returnValue; goto Failed; } if ( !AddAccessAllowedAceEx( newACL, ACL_REVISION, AceFlags, dwAccessMask, principalSID ) ) { hres = HRESULT_FROM_WIN32( GetLastError() ); goto Failed; } *ppAcl = newACL; if ( oldACL ) { delete [] oldACL; } return S_OK; Failed: // The new ACL will not be returned so free it! delete [] newACL; return hres; } HRESULT CSecurityDescriptor::RemovePrincipalFromACL(PACL pAcl, LPCTSTR pszPrincipal) { PSID principalSID = NULL; DWORD returnValue; returnValue = GetPrincipalSID(pszPrincipal, &principalSID); if (FAILED(returnValue)) return returnValue; returnValue = RemovePrincipalFromACL(pAcl, principalSID); delete [] principalSID; return FAILED(returnValue)?returnValue:S_OK; } HRESULT CSecurityDescriptor::RemovePrincipalFromACL(PACL pAcl, PSID principalSID) { ACL_SIZE_INFORMATION aclSizeInfo; ULONG i; LPVOID ace; ACCESS_ALLOWED_ACE *accessAllowedAce; ACCESS_DENIED_ACE *accessDeniedAce; SYSTEM_AUDIT_ACE *systemAuditAce; DWORD returnValue; ACE_HEADER *aceHeader; GetAclInformation(pAcl, (LPVOID) &aclSizeInfo, (DWORD) sizeof(ACL_SIZE_INFORMATION), AclSizeInformation); for (i = 0; i < aclSizeInfo.AceCount; i++) { if (!GetAce(pAcl, i, &ace)) { return HRESULT_FROM_WIN32( GetLastError() ); } aceHeader = (ACE_HEADER *) ace; if (aceHeader->AceType == ACCESS_ALLOWED_ACE_TYPE) { accessAllowedAce = (ACCESS_ALLOWED_ACE *) ace; if (EqualSid(principalSID, (PSID) &accessAllowedAce->SidStart)) { DeleteAce(pAcl, i); return S_OK; } } else if (aceHeader->AceType == ACCESS_DENIED_ACE_TYPE) { accessDeniedAce = (ACCESS_DENIED_ACE *) ace; if (EqualSid(principalSID, (PSID) &accessDeniedAce->SidStart)) { DeleteAce(pAcl, i); return S_OK; } } else if (aceHeader->AceType == SYSTEM_AUDIT_ACE_TYPE) { systemAuditAce = (SYSTEM_AUDIT_ACE *) ace; if (EqualSid(principalSID, (PSID) &systemAuditAce->SidStart)) { DeleteAce(pAcl, i); return S_OK; } } } return S_OK; } BOOL CSecurityDescriptor::DoesPrincipleHaveAce( LPCTSTR pszPrincipal ) { PSID principalSID = NULL; if ( FAILED( GetPrincipalSID( pszPrincipal, &principalSID ) ) ) { return FALSE; } return DoesPrincipleHaveAce( principalSID ); } // CSecurityDescriptor::DoesPrincipleHaveAce BOOL CSecurityDescriptor::DoesPrincipleHaveAce( PSID principalSID ) { ACL_SIZE_INFORMATION aclSizeInfo; ULONG i; LPVOID ace; ACCESS_ALLOWED_ACE *accessAllowedAce; ACCESS_DENIED_ACE *accessDeniedAce; SYSTEM_AUDIT_ACE *systemAuditAce; DWORD returnValue; ACE_HEADER *aceHeader; GetAclInformation( m_pDACL, ( LPVOID ) &aclSizeInfo, ( DWORD ) sizeof( ACL_SIZE_INFORMATION ), AclSizeInformation ); for (i = 0; i < aclSizeInfo.AceCount; i++) { if ( !GetAce( m_pDACL, i, &ace ) ) { return FALSE; } aceHeader = ( ACE_HEADER * ) ace; if ( aceHeader->AceType == ACCESS_ALLOWED_ACE_TYPE ) { accessAllowedAce = ( ACCESS_ALLOWED_ACE * ) ace; if ( EqualSid( principalSID, ( PSID ) &accessAllowedAce->SidStart ) ) { return TRUE; } } else if ( aceHeader->AceType == ACCESS_DENIED_ACE_TYPE ) { accessDeniedAce = ( ACCESS_DENIED_ACE * ) ace; if ( EqualSid( principalSID, ( PSID ) &accessDeniedAce->SidStart ) ) { return TRUE; } } else if ( aceHeader->AceType == SYSTEM_AUDIT_ACE_TYPE ) { systemAuditAce = ( SYSTEM_AUDIT_ACE * ) ace; if ( EqualSid( principalSID, ( PSID ) &systemAuditAce->SidStart ) ) { return TRUE; } } } return FALSE; } // CSecurityDescriptor::DoesPrincipleHaveAce HRESULT CSecurityDescriptor::SetPrivilege(LPCTSTR privilege, BOOL bEnable, HANDLE hToken) { HRESULT hr=S_OK; TOKEN_PRIVILEGES tpPrevious; TOKEN_PRIVILEGES tp; DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES); LUID luid; BOOL bOwnToken=FALSE; // if no token specified open process token if (hToken == 0) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto cleanup; } bOwnToken = TRUE; } if (!LookupPrivilegeValue(NULL, privilege, &luid )) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto cleanup; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = 0; if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, &cbPrevious)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto cleanup; } tpPrevious.PrivilegeCount = 1; tpPrevious.Privileges[0].Luid = luid; if (bEnable) tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED); else tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes); if (!AdjustTokenPrivileges(hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto cleanup; } cleanup: if (bOwnToken && hToken) { CloseHandle(hToken); } return hr; } LPTSTR CSecurityDescriptor::GenerateSDString(PSECURITY_DESCRIPTOR OPTIONAL pSd, DWORD OPTIONAL fSecInfo) { /*+++ Function : GenerateSDString Description: Uses SDDL to generate a SD string Parameters : pSd: Optional SD to convert fSecInfo: Optional requested security information flag Return : a pointer to LocalAlloc'eted string representation of SD NULL on error. Remarks : Must free returned string w/ LocalFree. Use GetLastError if you get back a NULL ---*/ PSECURITY_DESCRIPTOR pTmpSd = pSd ? pSd : m_pSD; LPTSTR pwsSd = NULL; if (!pTmpSd) { return NULL; } ConvertSecurityDescriptorToStringSecurityDescriptor(pTmpSd, SDDL_REVISION, fSecInfo, &pwsSd, NULL); return pwsSd; } PSID CSecurityDescriptor::ExtractAceSid( ACCESS_ALLOWED_ACE* pACE ) /*++ Routine Description (ExtractAceSid): Extract a Sid from an ace based on the ace's type Arguments: ACE in old format (ACCESS_ALLOWED_ACE) Return Value: ptr to a sid; Remarks: None. --*/ { PBYTE ptr = NULL; ASSERT ( pACE ); if ( pACE->Header.AceType <= ACCESS_MAX_MS_V2_ACE_TYPE ) { // // Simple case ACE // ptr = (PBYTE)&(pACE->SidStart); } else if ( pACE->Header.AceType <= ACCESS_MAX_MS_V3_ACE_TYPE ) { // // Compound ACE case // // PCOMPOUND_ACCESS_ALLOWED_ACE pObjAce = (PCOMPOUND_ACCESS_ALLOWED_ACE)pACE; // I think this case in term of typecasting is equivalent // to the previous one. Left for clarity, later can collapse down. ptr = (PBYTE)&(pACE->SidStart); } else if ( pACE->Header.AceType <= ACCESS_MAX_MS_V4_ACE_TYPE ) { // // Object ACEs // ACCESS_ALLOWED_OBJECT_ACE *pObjAce = (ACCESS_ALLOWED_OBJECT_ACE*)pACE; ptr = (PBYTE)&(pObjAce->ObjectType); if (pObjAce->Flags & ACE_OBJECT_TYPE_PRESENT) { ptr += sizeof(GUID); } if (pObjAce->Flags & ACE_INHERITED_OBJECT_TYPE_PRESENT) { ptr += sizeof(GUID); } } return (PSID)ptr; }
tilepal 0, GRAY, RED, WATER, WATER, GRAY, GRAY, WATER, WATER tilepal 0, WATER, WATER, WATER, WATER, WATER, WATER, BROWN, BROWN tilepal 0, WATER, RED, WATER, WATER, GRAY, GRAY, WATER, WATER tilepal 0, WATER, WATER, WATER, WATER, WATER, WATER, BROWN, BROWN tilepal 0, WATER, RED, RED, RED, RED, WATER, GRAY, GRAY tilepal 0, WATER, WATER, GRAY, GRAY, BROWN, BROWN, BROWN, BROWN tilepal 0, WATER, RED, RED, RED, RED, WATER, GRAY, WATER tilepal 0, GRAY, GRAY, BROWN, RED, BROWN, BROWN, BROWN, BROWN tilepal 0, RED, BROWN, RED, BROWN, BROWN, BROWN, RED, RED tilepal 0, WATER, WATER, WATER, RED, RED, RED, RED, WATER tilepal 0, BROWN, YELLOW, RED, BROWN, BROWN, BROWN, RED, RED tilepal 0, WATER, RED, RED, RED, RED, GRAY, RED, WATER rept 16 db $ff endr tilepal 1, GRAY, WATER, GRAY, WATER, WATER, WATER, ROOF, ROOF tilepal 1, YELLOW, YELLOW, GRAY, GRAY, WATER, WATER, RED, RED tilepal 1, GRAY, RED, RED, WATER, WATER, WATER, WATER, WATER tilepal 1, RED, GRAY, GRAY, GRAY, GREEN, YELLOW, RED, RED tilepal 1, GRAY, GRAY, RED, RED, WATER, WATER, GRAY, GRAY tilepal 1, YELLOW, YELLOW, BROWN, YELLOW, WATER, WATER, YELLOW, RED tilepal 1, GRAY, GRAY, RED, RED, GRAY, WATER, WATER, WATER tilepal 1, GRAY, GRAY, BROWN, YELLOW, RED, RED, YELLOW, RED tilepal 1, GRAY, GRAY, RED, RED, RED, RED, WATER, WATER tilepal 1, GRAY, GRAY, YELLOW, BROWN, WATER, WATER, GRAY, BROWN tilepal 1, RED, RED, RED, RED, RED, RED, GRAY, GRAY tilepal 1, YELLOW, YELLOW, GRAY, GRAY, GRAY, GRAY, GRAY, GRAY
#include "stdafx.h" #include "OggExtractor.h" #include <string> #include <sstream> #include <iomanip> OggDecryptor::OggDecryptor(TCHAR* lpInputPath, TCHAR* lpOutputDirectory) { m_source = File::CreateReader(lpInputPath); m_lpOutputDirectory = lpOutputDirectory; CreateDirectory(lpOutputDirectory, nullptr); } OggDecryptor::~OggDecryptor() { if (m_source && m_source->Opened()) m_source->Close(); if (m_writer && m_writer->Opened()) m_writer->Close(); } void OggDecryptor::Extract() { OggPageHeader pageHeader; uint8_t segmentLengths[MAX_OGG_SEGMENTS_COUNT]; uint8_t segment[MAX_OGG_SEGMENT_LENGTH]; while(m_source->FindU32(OGG_MAGIC_OGGS)) { // printf("Dumping file (%d)\n", m_fileNumber); if (m_source->IsEndOfFile()) break; m_source->Read(&pageHeader, sizeof(pageHeader)); const auto segmentsCount = pageHeader.PageSegments; if (pageHeader.IsNewPage()) { NextFile(); } else if (!m_writer && !m_writer->Opened()) { printf("WARN: Expecting new header, discard this page...\n"); } m_source->Read(segmentLengths, segmentsCount); m_writer->Write(&pageHeader, sizeof(pageHeader)); m_writer->Write(segmentLengths, segmentsCount); // 处理各个区段 for (int i = 0; i < segmentsCount; i++) { // printf("Dumping segment %d/%d...", i, segmentsCount); auto size = segmentLengths[i]; m_source->Read(segment, size); m_writer->Write(segment, size); // printf("ok!\n"); } } LogProgress::Done(); } void OggDecryptor::NextFile() { if (m_writer && m_writer->Opened()) m_writer->Close(); m_fileNumber++; std::wstringstream outputFileName; outputFileName << std::setw(3) << std::setfill(L'0') << m_fileNumber << L".ogg"; std::wstringstream outputFile; outputFile << m_lpOutputDirectory << L"\\" << outputFileName.str(); std::wstringstream outputLog; outputLog << L"Dumping " << outputFileName.str() << "..."; LogProgress::UpdateProgress(outputLog.str().c_str()); m_writer = File::CreateWriter(outputFile.str().c_str()); }
; A219190: Numbers of the form n*(5*n+1), where n = 0,-1,1,-2,2,-3,3,... ; 0,4,6,18,22,42,48,76,84,120,130,174,186,238,252,312,328,396,414,490,510,594,616,708,732,832,858,966,994,1110,1140,1264,1296,1428,1462,1602,1638,1786,1824,1980,2020,2184,2226,2398,2442,2622,2668,2856,2904,3100,3150,3354,3406,3618,3672,3892,3948,4176,4234,4470,4530,4774,4836,5088,5152,5412,5478,5746,5814,6090,6160,6444,6516,6808,6882,7182,7258,7566,7644,7960,8040,8364,8446,8778,8862,9202,9288,9636,9724,10080,10170,10534,10626,10998,11092,11472,11568,11956,12054,12450,12550,12954,13056,13468,13572,13992,14098,14526,14634,15070,15180,15624,15736,16188,16302,16762,16878,17346,17464,17940,18060,18544,18666,19158,19282,19782,19908,20416,20544,21060,21190,21714,21846,22378,22512,23052,23188,23736,23874,24430,24570,25134,25276,25848,25992,26572,26718,27306,27454,28050,28200,28804,28956,29568,29722,30342,30498,31126,31284,31920,32080,32724,32886,33538,33702,34362,34528,35196,35364,36040,36210,36894,37066,37758,37932,38632,38808,39516,39694,40410,40590,41314,41496,42228,42412,43152,43338,44086,44274,45030,45220,45984,46176,46948,47142,47922,48118,48906,49104,49900,50100,50904,51106,51918,52122,52942,53148,53976,54184,55020,55230,56074,56286,57138,57352,58212,58428,59296,59514,60390,60610,61494,61716,62608,62832,63732,63958,64866,65094,66010,66240,67164,67396,68328,68562,69502,69738,70686,70924,71880,72120,73084,73326,74298,74542,75522,75768,76756,77004,78000 mul $0,2 mov $2,$0 lpb $2,1 add $0,2 add $1,$0 trn $2,4 lpe
; A157106: 5651522n^2 - 2541672n + 285769. ; 3395619,17808513,43524451,80543433,128865459,188490529,259418643,341649801,435184003,540021249,656161539,783604873,922351251,1072400673,1233753139,1406408649,1590367203,1785628801,1992193443,2210061129,2439231859,2679705633,2931482451,3194562313,3468945219,3754631169,4051620163,4359912201,4679507283,5010405409,5352606579,5706110793,6070918051,6447028353,6834441699,7233158089,7643177523,8064500001,8497125523,8941054089,9396285699,9862820353,10340658051,10829798793,11330242579,11841989409,12365039283,12899392201,13445048163,14002007169,14570269219,15149834313,15740702451,16342873633,16956347859,17581125129,18217205443,18864588801,19523275203,20193264649,20874557139,21567152673,22271051251,22986252873,23712757539,24450565249,25199676003,25960089801,26731806643,27514826529,28309149459,29114775433,29931704451,30759936513,31599471619,32450309769,33312450963,34185895201,35070642483,35966692809,36874046179,37792702593,38722662051,39663924553,40616490099,41580358689,42555530323,43542005001,44539782723,45548863489,46569247299,47600934153,48643924051,49698216993,50763812979,51840712009,52928914083,54028419201,55139227363,56261338569,57394752819,58539470113,59695490451,60862813833,62041440259,63231369729,64432602243,65645137801,66868976403,68104118049,69350562739,70608310473,71877361251,73157715073,74449371939,75752331849,77066594803,78392160801,79729029843,81077201929,82436677059,83807455233,85189536451,86582920713,87987608019,89403598369,90830891763,92269488201,93719387683,95180590209,96653095779,98136904393,99632016051,101138430753,102656148499,104185169289,105725493123,107277120001,108840049923,110414282889,111999818899,113596657953,115204800051,116824245193,118454993379,120097044609,121750398883,123415056201,125091016563,126778279969,128476846419,130186715913,131907888451,133640364033,135384142659,137139224329,138905609043,140683296801,142472287603,144272581449,146084178339,147907078273,149741281251,151586787273,153443596339,155311708449,157191123603,159081841801,160983863043,162897187329,164821814659,166757745033,168704978451,170663514913,172633354419,174614496969,176606942563,178610691201,180625742883,182652097609,184689755379,186738716193,188798980051,190870546953,192953416899,195047589889,197153065923,199269845001,201397927123,203537312289,205688000499,207849991753,210023286051,212207883393,214403783779,216610987209,218829493683,221059303201,223300415763,225552831369,227816550019,230091571713,232377896451,234675524233,236984455059,239304688929,241636225843,243979065801,246333208803,248698654849,251075403939,253463456073,255862811251,258273469473,260695430739,263128695049,265573262403,268029132801,270496306243,272974782729,275464562259,277965644833,280478030451,283001719113,285536710819,288083005569,290640603363,293209504201,295789708083,298381215009,300984024979,303598137993,306223554051,308860273153,311508295299,314167620489,316838248723,319520180001,322213414323,324917951689,327633792099,330360935553,333099382051,335849131593,338610184179,341382539809,344166198483,346961160201,349767424963,352584992769 mov $1,$0 cal $1,157105 ; 137842n - 30996. pow $1,2 sub $1,11416067715 div $1,11303044 mul $1,3362 add $1,3395619
#include <iostream> using namespace std; int main() { int n = 3; int mat[n][n]; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { cin >> mat[i][j]; } } int linhaMagica[n] = {0}, colunaMagica[n] = {0}, diagMagica[2] = {0}; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { linhaMagica[i] += mat[i][j]; } } for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { colunaMagica[j] += mat[i][j]; } } for (int i=0; i<n; i++) { diagMagica[0] += mat[i][i]; } int k = 2; for (int i=0; i<n; i++) { diagMagica[1] += mat[i][k--]; } int ehLinMag = 1, ehColMag = 1, ehDiaMag = 1; for (int i=0; i<n-1; i++) { if (linhaMagica[i] != linhaMagica[i+1]) ehLinMag = 0; } for (int i=0; i<n-1; i++) { if (colunaMagica[i] != colunaMagica[i+1]) ehColMag = 0; } if (diagMagica[0] != diagMagica[1]) ehDiaMag = 0; if (ehDiaMag && ehColMag && ehLinMag) cout << "eh um quadrado magico" << endl; else cout << "nao eh um quadrado magico" << endl; }
include io.h cr equ 10 lf equ 13 .model small .stack 200h .data newline db cr,lf,0 string db 40 dup(?) str_in db ? prompt1 db cr,lf,'enter the string : ',0 prompt2 db cr,lf,'enter the character : ',0 result db ? .code strsearch proc mov cl,0 whiles: cmp Byte ptr[bx],0 je endwhiles cmp Byte ptr[bx],al je endwhiles inc bx inc cl jmp short whiles endwhiles: ret strsearch endp ;--------------------------------------------------------- main proc mov ax,@data mov ds,ax ;----------------------------------------------------- clrscr output prompt1 inputs string mov bx,offset string output prompt2 inputc str_in call strsearch mov ch,0 output newline itoa result,cx output result ;-------------------------------------------------------------- main endp mov ax,4c00h int 21h end main ;-------------------------------------------------------------------
SSAnneB1F_Script: jp EnableAutoTextBoxDrawing SSAnneB1F_TextPointers: db "@"
// Copyright (c) 2018, Smart Projects Holdings Ltd // All rights reserved. // See LICENSE file for license details. /* Unit tests for MAVLink messages parser/serializer. */ #include <ugcs/vsm/mavlink.h> #include <UnitTest++.h> using namespace ugcs::vsm; using namespace ugcs::vsm::mavlink; /* Define plain format of some message under test. */ struct Mav_param_request_read { int16_t param_index; uint8_t target_system; uint8_t target_component; char param_id[16]; }; void Check_message(Pld_param_request_read &msg, uint8_t target_system, uint8_t target_component, const char *param_id, int16_t param_index) { auto buf = msg.Get_buffer(); auto msg_buf = static_cast<const Mav_param_request_read *>(buf->Get_data()); CHECK_EQUAL(target_system, msg_buf->target_system); CHECK_EQUAL(target_component, msg_buf->target_component); CHECK(msg->param_id == param_id); CHECK_EQUAL(Le(param_index), msg_buf->param_index); } TEST(basic_functionality) { Mav_param_request_read msg_buf = {Le(static_cast<int16_t>(0x0102)), 1, 2, "param ID"}; Pld_param_request_read msg(&msg_buf, sizeof(msg_buf)); CHECK_EQUAL(sizeof(Mav_param_request_read), msg.Get_size_v1()); CHECK_EQUAL(1, msg->target_system); CHECK_EQUAL(2, msg->target_component); CHECK(msg->param_id == "param ID"); CHECK(msg->param_id.Get_string() == "param ID"); CHECK_EQUAL(0x0102, msg->param_index); CHECK_EQUAL(0x0102, msg->param_index.Get()); /* Assign to multi-byte value. */ msg->param_index = 0x0304; Check_message(msg, 1, 2, "param ID", 0x0304); msg->target_system = 5; Check_message(msg, 5, 2, "param ID", 0x0304); /* Assign string to characters array. */ msg->param_id = "012345678901234"; Check_message(msg, 5, 2, "012345678901234", 0x0304); msg->param_id = "0123456789012345"; Check_message(msg, 5, 2, "0123456789012345", 0x0304); /* Last character should be truncated. */ msg->param_id = "01234567890123456"; Check_message(msg, 5, 2, "0123456789012345", 0x0304); /* Check dumping. */ std::string str = msg.Dump(); const char *expected_str = "Message PARAM_REQUEST_READ (20 bytes)\n" "int16_t param_index: 772\n" "uint8_t target_system: 5\n" "uint8_t target_component: 2\n" "char param_id[16]: '0123456789012345'\n"; CHECK_EQUAL(expected_str, str.c_str()); /* Check reset. */ CHECK(!msg->param_index.Is_reset()); msg->param_index.Reset(); /* For int. */ CHECK_EQUAL(std::numeric_limits<int16_t>::max(), msg->param_index); CHECK(msg->param_index.Is_reset()); } TEST(version_field) { /* Check that version field is initialized automatically to current protocol * version. */ Pld_heartbeat msg; CHECK_EQUAL(VERSION, msg->mavlink_version); }
/* * IntelManager.cpp * * Created on: Apr 30, 2015 * Author: Rob Lyerly <rlyerly@vt.edu> */ #include <fstream> #include <sstream> #include <stdint.h> /* Linux system information */ #include <sys/utsname.h> #include "IntelManager.h" #include "Intel.h" #include "MSR.h" /* Object type conversions */ #define toIntel( devPtr ) ((IntelDevice*)devPtr) #define toRAPL( devPtr ) ((IntelRAPLDevice*)devPtr) #define toXeonPhi( devPtr ) () // TODO /* * Default constructor - initialize devices. */ IntelManager::IntelManager() { DEBUG(" IntelManager: available"); _initializeDevices(); } /* * Default destructor - close any RAPL file descriptors */ IntelManager::~IntelManager() { // nothing for now... } /* * Create objects for all Intel devices in the system. * * Intel CPUs: Parse /proc/cpuinfo & /sys/devices/system/cpu to create Intel * CPU devices. A device is created per-package, the measurement granularity * for RAPL. * * Intel Xeon Phi: TODO * * Note: IntelManager ONLY manages Intel devices (no ARM/AMD/etc)! */ void IntelManager::_initializeDevices() { // Initialize Intel CPU/RAPL devices std::ifstream cpuinfo; std::string line; IntelRAPLDevice* pkg = NULL; int curCPU = -1, curPackage = -1; bool skip = false; cpuinfo.open("/proc/cpuinfo"); if(!cpuinfo.is_open()) return; while(std::getline(cpuinfo, line)) { if(line.find("processor") != std::string::npos) curCPU++; // Add CPU after ensuring that it's Intel else if(line.find("vendor_id") != std::string::npos) { if(line.substr(line.find(':') + 2) == "GenuineIntel") // Ensure Intel CPU skip = false; else { DEBUG("IntelManager: skipping non-Intel CPU " << curCPU); skip = true; } } else if(!skip && line.find("model name") != std::string::npos) { // Get CPU package info std::stringstream ss; std::ifstream packageFile; int package; ss << "/sys/devices/system/cpu/cpu" << curCPU << "/topology/physical_package_id"; packageFile.open(ss.str().c_str()); packageFile >> package; packageFile.close(); if(package > curPackage) { if(pkg) _devices.push_back(pkg); pkg = new IntelRAPLDevice(); curPackage = package; } // Set name & add CPU to device std::string name = line.substr(line.find(':') + 2); if(pkg->name() == "N/A") pkg->setName(name); pkg->addCPU(curCPU); } else if(!skip && line.find("cpu MHz") != std::string::npos) { if(pkg->clockSpeed() == 0) { std::stringstream ss; unsigned mhz; ss << line.substr(line.find(':') + 2); ss >> mhz; pkg->setClockSpeed(mhz); } } } if(pkg) _devices.push_back(pkg); cpuinfo.close(); // TODO Populate Xeon Phi device(s) _numDevices = _devices.size(); // Check for power control for(unsigned i = 0; i < _numDevices; i++) { retval_t retval; switch(toIntel(_devices[i])->intelDevType()) { case INTEL_RAPL: retval = toRAPL(_devices[i])->initializeRAPL(); if(retval) { DEBUG(retvalStr[retval] << " (can't monitor power using RAPL)"); continue; } break; case XEON_PHI: // TODO Xeon Phi break; } } } /* * Return the Linux kernel version. * * @return the Linux kernel version */ std::string IntelManager::version() const { struct utsname info; assert(!uname(&info)); std::string version(info.release); return version; } /* * Return human-readable information about the specified device. * * @param dev the device number */ std::string IntelManager::getDeviceInfo(unsigned dev) const { std::stringstream ss; if(dev >= _numDevices) { ss << "Invalid device number " << dev << ", must be 0"; if(_numDevices > 1) ss << " - " << (_numDevices - 1); } else { ss << _devices[dev]->name() << " (" << _devices[dev]->clockSpeed() << "MHz)"; if(toIntel(_devices[dev])->intelDevType() == INTEL_RAPL) ss << " - " << toRAPL(_devices[dev])->numCPUs() << " core(s)"; } return ss.str(); } /* * Start power monitoring service for all Intel devices associated with the * manager. */ void IntelManager::startPowerMonitoring() { for(unsigned i = 0; i < _devices.size(); i++) { if(_devices[i]->measurePower()) { switch(toIntel(_devices[i])->intelDevType()) { case INTEL_RAPL: assert(_devices[i]->startEnergyAccounting() == SUCCESS); break; case XEON_PHI: assert("Xeon Phi not yet implemented" && false); break; } } } } /* * Measure power for each Intel device & update energy accounting. * * @param elapsedTime the time since last reading */ void IntelManager::measurePower(struct timespec& elapsedTime) { for(unsigned i = 0; i < _devices.size(); i++) { if(_devices[i]->measurePower()) { switch(toIntel(_devices[i])->intelDevType()) { case INTEL_RAPL: assert(toRAPL(_devices[i])->addEnergyConsumption(elapsedTime) == SUCCESS); break; case XEON_PHI: _devices[i]->addEnergyConsumption(_measureXeonPhiPower(_devices[i]), elapsedTime); break; } } } } unsigned IntelManager::_measureXeonPhiPower(Device* dev) { //TODO ERR("measuring Xeon Phi power is unimplemented"); }
class Solution { public: vector<int> numMovesStones(int a, int b, int c) { vector<int> v = {a, b, c}; sort(v.begin(), v.end()); vector<int> sizes = {v[2] - v[1] - 1, v[1] - v[0] - 1}; int minMoves = 2; if(sizes[0] == 0 && sizes[1] == 0){ minMoves = 0; }else if(sizes[0] <= 1 || sizes[1] <= 1){ minMoves = 1; } int maxMoves = sizes[0] + sizes[1]; return {minMoves, maxMoves}; } };
#ifndef COMPILER_SCANNER_HPP #define COMPILER_SCANNER_HPP #include <compiler/token.hpp> // Scanner struct Scanner { const char *start; const char *current; int line; int column; }; extern Scanner g_scanner; extern void scanner_init(const char *source); extern Token scan_token(); #endif
; A153600: a(n) = ((9 + sqrt(3))^n - (9 - sqrt(3))^n)/(2*sqrt(3)). ; Submitted by Jon Maiga ; 1,18,246,3024,35244,398520,4424328,48553344,528862608,5732366112,61931306592,667638961920,7186859400384,77287630177152,830602309958784,8922406425440256,95816335481139456,1028746337476170240,11043759907042186752,118545464003618082816,1272405079315834924032,13656745235402818172928,146573818050615603038208,1573102596549661037199360,16883088929945881632608256,181193598208152308485398528,1944603831210962785393729536,20869768301561450075226046464,223976730593651004093357932544 mov $3,1 lpb $0 sub $0,1 add $2,$3 mul $3,6 sub $3,$2 mul $2,13 lpe add $3,$2 mov $0,$3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ZX_01_OUTPUT_FZX ; romless driver for proportional fzx fonts ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Windowed output terminal for proportional fzx fonts. ; Implements tty_z88dk terminal emulation. ; ; ;;;;;;;;;;;;;;;;;;;; ; DRIVER CLASS DIAGRAM ; ;;;;;;;;;;;;;;;;;;;; ; ; CONSOLE_01_OUTPUT_TERMINAL (root, abstract) ; CONSOLE_01_OUTPUT_TERMINAL_FZX (abstract) ; ZX_01_OUTPUT_FZX (concrete) ; ZX_01_OUTPUT_FZX_TTY_Z88DK (concrete) ; ; Can be instantiated to implement a CONSOLE_01_OUTPUT_TERMINAL. ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; MESSAGES CONSUMED FROM STDIO ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; * STDIO_MSG_PUTC ; Generates multiple OTERM_MSG_PUTC messages. ; ; * STDIO_MSG_WRIT ; Generates multiple OTERM_MSG_PUTC messages. ; ; * STDIO_MSG_SEEK -> no error, do nothing ; * STDIO_MSG_FLSH -> no error, do nothing ; * STDIO_MSG_ICTL ; * STDIO_MSG_CLOS -> no error, do nothing ; ; Any other messages are reported as errors via ; error_enotsup_zc ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; * OTERM_MSG_PUTC ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; MESSAGES CONSUMED FROM CONSOLE_01_INPUT_TERMINAL ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; * ITERM_MSG_PUTC ; * ITERM_MSG_PRINT_CURSOR ; * ITERM_MSG_BS ; * ITERM_MSG_BS_PWD ; * ITERM_MSG_ERASE_CURSOR ; * ITERM_MSG_ERASE_CURSOR_PWD ; * ITERM_MSG_READLINE_BEGIN ; * ITERM_MSG_READLINE_END ; * ITERM_MSG_BELL ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL_FZX ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; * OTERM_MSG_TTY ; * OTERM_MSG_BELL ; * OTERM_MSG_SCROLL ; * OTERM_MSG_CLS ; * OTERM_MSG_PAUSE ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; MESSAGES CONSUMED FROM ZX_01_OUTPUT_FZX ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; * OTERM_MSG_SCROLL ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; IOCTLs UNDERSTOOD BY THIS DRIVER ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; * IOCTL_OTERM_CRLF ; enable / disable crlf processing ; ; * IOCTL_OTERM_BELL ; enable / disable terminal bell ; ; * IOCTL_OTERM_SIGNAL ; enable / disable signal bell ; ; * IOCTL_OTERM_COOK ; enable / disable cook mode (tty emulation) ; ; * IOCTL_OTERM_PAUSE ; enable / disable pause when window filled ; ; * IOCTL_OTERM_PAGE ; select scroll or page mode ; ; * IOCTL_OTERM_CLEAR ; enable / disable clear window when in page mode ; ; * IOCTL_OTERM_CLS ; clear window, set (x,y) = (0,0) ; ; * IOCTL_OTERM_RESET_SCROLL ; reset scroll count ; ; THE FZX WINDOW IS THE AREA THAT IS CLEARED AND SCROLLED ; ; * IOCTL_OTERM_GET_WINDOW_COORD ; get coord of top left corner of window ; ; * IOCTL_OTERM_SET_WINDOW_COORD ; set coord of top left corner of window ; ; * IOCTL_OTERM_GET_WINDOW_RECT ; get window size ; ; * IOCTL_OTERM_SET_WINDOW_RECT ; set window size ; ; * IOCTL_OTERM_GET_CURSOR_COORD ; ; * IOCTL_OTERM_SET_CURSOR_COORD ; ; * IOCTL_OTERM_GET_OTERM ; ; * IOCTL_OTERM_SCROLL ; ; * IOCTL_OTERM_FONT ; ; THE FZX PAPER IS THE AREA WHERE PRINTING OCCURS ; THE FZX WINDOW CONTAINS THE FZX PAPER ; ; * IOCTL_OTERM_FZX_GET_PAPER_COORD ; get coord of top left corner of paper ; ; * IOCTL_OTERM_FZX_SET_PAPER_COORD ; set coord of top left corner of paper ; ; * IOCTL_OTERM_FZX_GET_PAPER_RECT ; get paper size ; ; * IOCTL_OTERM_FZX_SET_PAPER_RECT ; set paper size ; ; * IOCTL_OTERM_FZX_LEFT_MARGIN ; ; * IOCTL_OTERM_FZX_LINE_SPACING ; ; * IOCTL_OTERM_FZX_SPACE_EXPAND ; ; * IOCTL_OTERM_FZX_GET_FZX_STATE ; ; * IOCTL_OTERM_FZX_SET_FZX_STATE ; ; * IOCTL_OTERM_BCOLOR ; ; * IOCTL_OTERM_FCOLOR ; ; * IOCTL_OTERM_FMASK ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;; ; BYTES RESERVED IN FDSTRUCT ; ;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; offset (wrt FDSTRUCT.JP) description ; ; 8..13 mutex ; 14..15 reserved ; 16 window.x ; 17 window.width ; 18 window.y ; 19 window.height ; 20 scroll_limit ; 21 line_spacing ; 22 temp: cursor ascii code ; 23..24 temp: fzx_draw mode ; 25..26 temp: edit x coord ; 27..28 temp: edit y coord ; 29 temp: space_expand ; ; 30 JP ; 31..32 fzx_draw ; 33..34 struct fzx_font * ; 35..36 x coordinate ; 37..38 y coordinate ; 39..40 paper.x ; 41..42 paper.width ; 43..44 paper.y ; 45..46 paper.height ; 47..48 left_margin ; 49 space_expand ; 50..51 reserved ; 52 text colour ; 53 text colour mask (set bits = keep bgnd) ; 54 background colour (cls colour) ; 55 tty_z88dk.call (205) ; 56..57 tty_z88dk.state ; 58 tty_z88dk.action ; 59 tty_z88dk.param_1 ; 60 tty_z88dk.param_2 SECTION code_driver SECTION code_driver_terminal_output PUBLIC zx_01_output_fzx_tty_z88dk EXTERN OTERM_MSG_TTY, STDIO_MSG_FLSH, STDIO_MSG_ICTL EXTERN zx_01_output_fzx EXTERN zx_01_output_fzx_tty_z88dk_oterm_msg_tty EXTERN zx_01_output_fzx_tty_z88dk_stdio_msg_flsh EXTERN zx_01_output_fzx_tty_z88dk_stdio_msg_ictl zx_01_output_fzx_tty_z88dk: cp OTERM_MSG_TTY jp z, zx_01_output_fzx_tty_z88dk_oterm_msg_tty cp STDIO_MSG_FLSH jp z, zx_01_output_fzx_tty_z88dk_stdio_msg_flsh cp STDIO_MSG_ICTL jp z, zx_01_output_fzx_tty_z88dk_stdio_msg_ictl jp zx_01_output_fzx ; forward to library
/*! * @brief General database interface * * @copyright Copyright (c) 2015-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file database.cpp */ #include "database/file_database.hpp" #include "generic/assertions.hpp" #include "logger/logger.hpp" #include "logger/logger_factory.hpp" #include <cstdint> #include <thread> using namespace database; using namespace generic; const std::chrono::seconds Database::NEVER{INT64_MAX}; const std::string Database::EMPTY{""}; std::string Database::default_location = "/var/opt/psme"; void Database::set_default_location(const std::string& location) { default_location = location; } Database::SPtr Database::create(const std::string& name, bool with_policy, const std::string& location) { std::lock_guard<std::recursive_mutex> lock(mutex); /* check if database is already created */ for (auto& db : databases) { if (db->get_name() == name) { log_error("db", "Database '" << name << "' already created"); assert(FAIL("Database already created")); return db; } } /* proper database type is to be created here.. Currently only FileDatabase is handled */ const std::string n = (name.substr(0, 1) == "*") ? "" : name; SPtr added{new FileDatabase(n, with_policy, location.empty() ? default_location : location)}; databases.push_back(added); return added; } std::recursive_mutex Database::mutex{}; Database::Databases Database::databases{}; Database::~Database() { } Database::Database(const std::string& _name) : name(_name) { } const std::string& Database::get_name() const { return name; } void Database::remove() { std::lock_guard<std::recursive_mutex> lock(mutex); Databases::iterator it; for (it = databases.begin(); it != databases.end(); it++) { if ((*it)->get_name() == get_name()) { databases.erase(it); return; } } log_error("db", "Database " << get_name() << " already removed"); } unsigned Database::invalidate_all(std::chrono::seconds interval) { SPtr db{Database::create("*retention", true)}; AlwaysMatchKey key{}; /* invalidate valid entries, remove outdated. Don't touch non related ones */ auto ret = db->cleanup(key, interval); db->remove(); return ret; } unsigned Database::remove_outdated(std::chrono::seconds interval) { SPtr db{Database::create("*retention", true)}; AlwaysMatchKey key{}; /* remove outdated files, don't touch non related ones */ unsigned ret = db->wipe_outdated(key, interval); db->remove(); return ret; } Serializable::Serializable() { } Serializable::~Serializable() { } std::ostream& database::operator<<(std::ostream& stream, const Serializable& val) { stream << val.serialize(); return stream; } String::String() : m_str("") { } String::String(const std::string& str) : m_str(str) { } String::String(std::string&& str) : m_str(std::move(str)) { } String& String::operator=(const std::string& str) { m_str = str; return *this; } String& String::operator=(std::string&& str) { m_str = std::move(str); return *this; } std::ostream& database::operator<<(std::ostream& stream, const String& str) { stream << str.m_str; return stream; } std::string String::serialize() const { return m_str; } bool String::unserialize(const std::string& str) { m_str = str; return true; } std::string UuidKey::serialize() const { if (!parent.empty()) { return parent + "." + uuid; } return uuid; } bool UuidKey::unserialize(const std::string& str) { size_t pos = str.find('.'); if (pos != std::string::npos) { parent = str.substr(0, pos); uuid = str.substr(pos + 1); } else { parent = ""; uuid = str; } return true; } std::string IdValue::serialize() const { if (id == 0) { return ""; } return std::to_string(id); } bool IdValue::unserialize(const std::string& str) { if (str.empty()) { return false; } /*! @todo util for stoul, etc.. with (range) checking */ id = std::stoul(str); return true; } std::string ResourceLastKey::serialize() const { return resource + "." + parent + "." + ResourceLastKey::LAST; } bool ResourceLastKey::unserialize(const std::string& str) { size_t last = str.rfind(std::string(".") + ResourceLastKey::LAST); if (std::string::npos == last) { return false; } size_t uuid = str.rfind('.', last - 1); if (std::string::npos == uuid) { return false; } /* check if data related the parent */ if (parent != str.substr(uuid + 1, last - uuid - 1)) { return false; } resource = str.substr(0, uuid); return true; } std::string AlwaysMatchKey::serialize() const { assert(FAIL("Intended to be used only to iterate over all data")); throw 0; } bool AlwaysMatchKey::unserialize(const std::string&) { return true; } const std::string ResourceLastKey::LAST{"last"};
/** * Copyright © 2013 - 2015 MNMLSTC * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this software except in compliance with the License. You may * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef CORE_INTERNAL_HPP #define CORE_INTERNAL_HPP /* This is a header containing common implementation specific code, to * reduce the complexity of the other headers, especially those that are * closely intertwined, such as <core/functional.hpp> and <core/type_traits.hpp> * * Additionally, some of this code is duplicated elsewhere (such as class_of, * and meta::identity), but aliases are placed to lessen any impact that this * might have. */ #include <type_traits> #include <functional> #include <utility> #include <ciso646> #include "meta.hpp" namespace core { inline namespace v2 { namespace impl { template <class T, class Void, template <class...> class, class...> struct make_detect : meta::identity<T> { using value_t = ::std::false_type; }; template <class T, template <class...> class U, class... Args> struct make_detect<T, meta::deduce<U<Args...>>, U, Args...> : meta::identity<U<Args...>> { using value_t = ::std::true_type; }; /* extremely useful custom type traits */ template <class T> struct class_of : meta::identity<T> { }; template <class Signature, class T> struct class_of<Signature T::*> : meta::identity<T> { }; /* aliases */ template <class T> using class_of_t = typename class_of<T>::type; template <class T> using decay_t = typename ::std::decay<T>::type; template <class T> using remove_reference_t = typename ::std::remove_reference<T>::type; template <bool B, class T = void> using enable_if_t = typename ::std::enable_if<B, T>::type; /* is_nothrow_swappable plumbing */ using ::std::declval; using ::std::swap; // MSVC 2015 workaround template <class T, class U> struct is_swappable_with { template <class X, class Y> static auto test (void*) noexcept(true) -> decltype( swap(declval<X&>(), declval<Y&>()) ); template <class, class> static void test (...) noexcept(false); static constexpr bool value = noexcept(test<T, U>(nullptr)); }; // MSVC 2015 workaround template <class T, class U> struct is_noexcept_swappable_with { template < class X, class Y, bool B=noexcept(swap(declval<X&>(), declval<Y&>())) > static void test (enable_if_t<B>*) noexcept(true); template <class, class> static void test (...) noexcept(false); static constexpr bool value = noexcept(test<T, U>(nullptr)); }; template <class, class, class=void> struct is_swappable : ::std::false_type { }; template <class T, class U> struct is_swappable< T, U, meta::deduce< is_swappable_with<T, U>, is_swappable_with<U, T> > > : ::std::true_type { }; template <class T, class U=T> struct is_nothrow_swappable : meta::all_t< is_swappable<T, U>::value, is_noexcept_swappable_with<T, U>::value, is_noexcept_swappable_with<U, T>::value > { }; /* * If I can't amuse myself when working with C++ templates, then life isn't * worth living. Bury me with my chevrons. */ template <class T> constexpr T&& pass (remove_reference_t<T>& t) noexcept { return static_cast<T&&>(t); } template <class T> constexpr T&& pass (remove_reference_t<T>&& t) noexcept { return static_cast<T&&>(t); } /* INVOKE pseudo-expression plumbing, *much* more simplified than previous * versions of Core */ struct undefined { constexpr undefined (...) noexcept { } }; /* We get some weird warnings under clang, so we actually give these functions * a body to get rid of it. */ template <class... Args> constexpr undefined INVOKE (undefined, Args&&...) noexcept { return undefined { }; } template <class Functor, class... Args> constexpr auto INVOKE (Functor&& f, Args&&... args) -> enable_if_t< not ::std::is_member_pointer<decay_t<Functor>>::value, decltype(pass<Functor>(f)(pass<Args>(args)...)) > { return pass<Functor>(f)(pass<Args>(args)...); } template <class Functor, class... Args> auto INVOKE (Functor&& f, Args&&... args) -> enable_if_t< ::std::is_member_pointer<decay_t<Functor>>::value, decltype(::std::mem_fn(pass<Functor>(f))(pass<Args>(args)...)) > { return ::std::mem_fn(pass<Functor>(f))(pass<Args>(args)...); } template <bool, class...> struct invoke_of { }; template <class... Args> struct invoke_of<true, Args...> : meta::identity<decltype(INVOKE(declval<Args>()...))> { }; }}} /* namespace core::v2::impl */ #endif /* CORE_INTERNAL_HPP */
; ; CPC Maths Routines ; ; August 2003 **_|warp6|_** <kbaccam /at/ free.fr> ; ; $Id: pow10.asm,v 1.2 2009/06/22 21:44:17 dom Exp $ ; INCLUDE "cpcfirm.def" INCLUDE "cpcfp.def" XLIB pow10 XDEF pow10c LIB float XREF fa .pow10 ld hl,1 call float ld hl,2 add hl,sp ld a,(hl) ld hl,fa+1 call firmware .pow10c defw CPCFP_FLO_POW10 ret
; A315731: Coordination sequence Gal.5.301.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; Submitted by Simon Strandgaard ; 1,6,12,18,22,28,32,38,44,50,56,62,68,72,78,82,88,94,100,106,112,118,122,128,132,138,144,150,156,162,168,172,178,182,188,194,200,206,212,218,222,228,232,238,244,250,256,262,268,272 mov $1,$0 seq $1,311612 ; Coordination sequence Gal.5.98.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. mov $2,$0 mul $0,6 sub $0,1 mod $0,$1 add $0,1 mul $2,4 add $0,$2
;Lines beginning with a semicolon (like this one) are Comments, and not part of the game. Information in such lines represent pieces which existed in vanilla, but have been ;removed or replaced by this hack. ; See constants/pokemon_data_constants.asm ; The max number of evolutions per monster is MAX_EVOLUTIONS EvosMovesPointerTable: table_width 2, EvosMovesPointerTable dw RhydonEvosMoves dw KangaskhanEvosMoves dw NidoranMEvosMoves dw ClefairyEvosMoves dw SpearowEvosMoves dw VoltorbEvosMoves dw NidokingEvosMoves dw SlowbroEvosMoves dw IvysaurEvosMoves dw ExeggutorEvosMoves dw LickitungEvosMoves dw ExeggcuteEvosMoves dw GrimerEvosMoves dw GengarEvosMoves dw NidoranFEvosMoves dw NidoqueenEvosMoves dw CuboneEvosMoves dw RhyhornEvosMoves dw LaprasEvosMoves dw ArcanineEvosMoves dw MewEvosMoves dw GyaradosEvosMoves dw ShellderEvosMoves dw TentacoolEvosMoves dw GastlyEvosMoves dw ScytherEvosMoves dw StaryuEvosMoves dw BlastoiseEvosMoves dw PinsirEvosMoves dw TangelaEvosMoves dw MissingNo1FEvosMoves dw MissingNo20EvosMoves dw GrowlitheEvosMoves dw OnixEvosMoves dw FearowEvosMoves dw PidgeyEvosMoves dw SlowpokeEvosMoves dw KadabraEvosMoves dw GravelerEvosMoves dw ChanseyEvosMoves dw MachokeEvosMoves dw MrMimeEvosMoves dw HitmonleeEvosMoves dw HitmonchanEvosMoves dw ArbokEvosMoves dw ParasectEvosMoves dw PsyduckEvosMoves dw DrowzeeEvosMoves dw GolemEvosMoves dw MissingNo32EvosMoves dw MagmarEvosMoves dw MissingNo34EvosMoves dw ElectabuzzEvosMoves dw MagnetonEvosMoves dw KoffingEvosMoves dw MissingNo38EvosMoves dw MankeyEvosMoves dw SeelEvosMoves dw DiglettEvosMoves dw TaurosEvosMoves dw MissingNo3DEvosMoves dw MissingNo3EEvosMoves dw MissingNo3FEvosMoves dw FarfetchdEvosMoves dw VenonatEvosMoves dw DragoniteEvosMoves dw MissingNo43EvosMoves dw MissingNo44EvosMoves dw MissingNo45EvosMoves dw DoduoEvosMoves dw PoliwagEvosMoves dw JynxEvosMoves dw MoltresEvosMoves dw ArticunoEvosMoves dw ZapdosEvosMoves dw DittoEvosMoves dw MeowthEvosMoves dw KrabbyEvosMoves dw MissingNo4FEvosMoves dw MissingNo50EvosMoves dw MissingNo51EvosMoves dw VulpixEvosMoves dw NinetalesEvosMoves dw PikachuEvosMoves dw RaichuEvosMoves dw MissingNo56EvosMoves dw MissingNo57EvosMoves dw DratiniEvosMoves dw DragonairEvosMoves dw KabutoEvosMoves dw KabutopsEvosMoves dw HorseaEvosMoves dw SeadraEvosMoves dw MissingNo5EEvosMoves dw MissingNo5FEvosMoves dw SandshrewEvosMoves dw SandslashEvosMoves dw OmanyteEvosMoves dw OmastarEvosMoves dw JigglypuffEvosMoves dw WigglytuffEvosMoves dw EeveeEvosMoves dw FlareonEvosMoves dw JolteonEvosMoves dw VaporeonEvosMoves dw MachopEvosMoves dw ZubatEvosMoves dw EkansEvosMoves dw ParasEvosMoves dw PoliwhirlEvosMoves dw PoliwrathEvosMoves dw WeedleEvosMoves dw KakunaEvosMoves dw BeedrillEvosMoves dw MissingNo73EvosMoves dw DodrioEvosMoves dw PrimeapeEvosMoves dw DugtrioEvosMoves dw VenomothEvosMoves dw DewgongEvosMoves dw MissingNo79EvosMoves dw MissingNo7AEvosMoves dw CaterpieEvosMoves dw MetapodEvosMoves dw ButterfreeEvosMoves dw MachampEvosMoves dw MissingNo7FEvosMoves dw GolduckEvosMoves dw HypnoEvosMoves dw GolbatEvosMoves dw MewtwoEvosMoves dw SnorlaxEvosMoves dw MagikarpEvosMoves dw MissingNo86EvosMoves dw MissingNo87EvosMoves dw MukEvosMoves dw MissingNo8AEvosMoves dw KinglerEvosMoves dw CloysterEvosMoves dw MissingNo8CEvosMoves dw ElectrodeEvosMoves dw ClefableEvosMoves dw WeezingEvosMoves dw PersianEvosMoves dw MarowakEvosMoves dw MissingNo92EvosMoves dw HaunterEvosMoves dw AbraEvosMoves dw AlakazamEvosMoves dw PidgeottoEvosMoves dw PidgeotEvosMoves dw StarmieEvosMoves dw BulbasaurEvosMoves dw VenusaurEvosMoves dw TentacruelEvosMoves dw MissingNo9CEvosMoves dw GoldeenEvosMoves dw SeakingEvosMoves dw MissingNo9FEvosMoves dw MissingNoA0EvosMoves dw MissingNoA1EvosMoves dw MissingNoA2EvosMoves dw PonytaEvosMoves dw RapidashEvosMoves dw RattataEvosMoves dw RaticateEvosMoves dw NidorinoEvosMoves dw NidorinaEvosMoves dw GeodudeEvosMoves dw PorygonEvosMoves dw AerodactylEvosMoves dw MissingNoACEvosMoves dw MagnemiteEvosMoves dw MissingNoAEEvosMoves dw MissingNoAFEvosMoves dw CharmanderEvosMoves dw SquirtleEvosMoves dw CharmeleonEvosMoves dw WartortleEvosMoves dw CharizardEvosMoves dw MissingNoB5EvosMoves dw FossilKabutopsEvosMoves dw FossilAerodactylEvosMoves dw MonGhostEvosMoves dw OddishEvosMoves dw GloomEvosMoves dw VileplumeEvosMoves dw BellsproutEvosMoves dw WeepinbellEvosMoves dw VictreebelEvosMoves assert_table_length NUM_POKEMON_INDEXES RhydonEvosMoves: ; Evolutions db 0 ; Learnset db 43, HEADBUTT db 48, ROAR db 53, SUBMISSION db 61, HORN_DRILL db 68, SLAM db 77, SWORDS_DANCE db 0 KangaskhanEvosMoves: ; Evolutions db 0 ; Learnset db 28, BITE db 35, SCREECH db 46, MEGA_PUNCH db 54, FURY_SWIPES db 62, DIZZY_PUNCH db 0 NidoranMEvosMoves: ; Evolutions db EV_LEVEL, 16, NIDORINO db 0 ; Learnset db 8, HORN_ATTACK db 14, POISON_STING db 21, FOCUS_ENERGY ;db 29, FURY_ATTACK ;db 36, HORN_DRILL ;db 43, DOUBLE_KICK db 0 ClefairyEvosMoves: ; Evolutions db EV_ITEM, MOON_STONE, 1, CLEFABLE db 0 ; Learnset db 11, SING db 14, DEFENSE_CURL db 18, DOUBLESLAP db 20, TRI_ATTACK db 24, MINIMIZE db 27, METRONOME db 32, EARTHQUAKE db 41, LIGHT_SCREEN db 48, REFLECT db 55, MEDITATE db 0 SpearowEvosMoves: ; Evolutions db EV_LEVEL, 20, FEAROW db 0 ; Learnset db 9, LEER db 15, FURY_ATTACK db 22, MIRROR_MOVE db 29, DRILL_PECK db 36, AGILITY db 0 VoltorbEvosMoves: ; Evolutions db EV_LEVEL, 30, ELECTRODE db 0 ; Learnset db 14, SONICBOOM db 18, SELFDESTRUCT db 23, LIGHT_SCREEN db 29, SWIFT db 33, THUNDERBOLT db 0 NidokingEvosMoves: ; Evolutions db 0 ; Learnset db 38, HAZE db 50, ROAR db 62, GUILLOTINE db 0 SlowbroEvosMoves: ; Evolutions db 0 ; Learnset db 38, SUBSTITUTE db 42, GROWTH db 47, CONSTRICT db 53, KINESIS db 57, LICK db 64, DOUBLE_EDGE db 75, COUNTER db 0 IvysaurEvosMoves: ; Evolutions db EV_LEVEL, 32, VENUSAUR db 0 ; Learnset db 17, ACID_ARMOR db 23, WRAP db 32, POISON_GAS db 40, SOLARBEAM db 48, MEGA_DRAIN db 56, SLEEP_POWDER ;db 64, SOLARBEAM db 0 ExeggutorEvosMoves: ; Evolutions db 0 ; Learnset ;db 28, STOMP db 0 LickitungEvosMoves: ; Evolutions db 0 ; Learnset db 17, DEFENSE_CURL db 23, DISABLE db 28, BITE db 35, SLAM db 44, SEISMIC_TOSS db 0 ExeggcuteEvosMoves: ; Evolutions db EV_ITEM, LEAF_STONE, 1, EXEGGUTOR db 0 ; Learnset db 35, SOFTBOILED db 38, LEECH_SEED db 43, STUN_SPORE db 46, EARTHQUAKE db 49, POISONPOWDER db 52, SOLARBEAM db 56, PSYCHIC_M db 58, SLEEP_POWDER db 65, METRONOME db 73, STOMP db 0 GrimerEvosMoves: ; Evolutions db EV_LEVEL, 38, MUK db 0 ; Learnset db 26, POISON_GAS db 33, MINIMIZE db 35, SLUDGE db 40, SUBMISSION db 46, SCREECH db 52, ACID_ARMOR db 0 GengarEvosMoves: ; Evolutions db 0 ; Learnset db 46, SUPER_FANG db 50, HYPER_FANG db 0 NidoranFEvosMoves: ; Evolutions db EV_LEVEL, 16, NIDORINA db 0 ; Learnset db 8, SCRATCH db 14, POISON_STING db 21, BIDE ;db 29, BITE ;db 36, FURY_SWIPES ;db 43, DOUBLE_KICK db 0 NidoqueenEvosMoves: ; Evolutions db 0 ; Learnset db 38, MIST db 50, RAGE db 62, FISSURE db 0 CuboneEvosMoves: ; Evolutions db EV_LEVEL, 38, MAROWAK db 0 ; Learnset db 28, SKULL_BASH db 33, FOCUS_ENERGY db 37, THRASH db 40, BONEMERANG db 48, RAGE db 0 RhyhornEvosMoves: ; Evolutions db EV_LEVEL, 42, RHYDON db 0 ; Learnset db 30, STOMP db 35, TAIL_WHIP db 40, FURY_ATTACK db 45, HORN_DRILL db 50, LEER db 55, TAKE_DOWN db 0 LaprasEvosMoves: ; Evolutions db 0 ; Learnset db 36, SING db 40, MIST db 45, BODY_SLAM db 51, CONFUSE_RAY db 58, ICE_BEAM db 66, HYDRO_PUMP db 0 ArcanineEvosMoves: ; Evolutions db 0 ; Learnset db 0 MewEvosMoves: ; Evolutions db 0 ; Learnset db 10, TRANSFORM db 20, MEGA_PUNCH db 30, METRONOME db 40, PSYCHIC_M db 0 GyaradosEvosMoves: ; Evolutions db 0 ; Learnset db 21, BITE db 25, DRAGON_RAGE db 32, WRAP db 41, HYDRO_PUMP db 52, HYPER_BEAM db 0 ShellderEvosMoves: ; Evolutions db EV_ITEM, WATER_STONE, 1, CLOYSTER db 0 ; Learnset db 26, SUPERSONIC db 33, CLAMP db 40, LEER db 48, SPIKE_CANNON db 49, BUBBLEBEAM db 51, LIGHT_SCREEN db 53, REFLECT db 56, CONSTRICT db 60, ICE_BEAM db 62, COUNTER db 0 TentacoolEvosMoves: ; Evolutions db EV_LEVEL, 40, TENTACRUEL db 0 ; Learnset db 7, SUPERSONIC db 13, POISON_STING db 35, WRAP db 39, WATER_GUN db 43, CONSTRICT db 45, BARRIER db 50, SCREECH db 57, HYDRO_PUMP db 0 GastlyEvosMoves: ; Evolutions db EV_LEVEL, 25, HAUNTER db 0 ; Learnset db 21, MINIMIZE db 23, GLARE db 0 ScytherEvosMoves: ; Evolutions db 0 ; Learnset db 9, LEER db 15, FOCUS_ENERGY db 20, DOUBLE_TEAM db 29, SLASH db 35, SWORDS_DANCE db 42, FURY_SWIPES db 0 StaryuEvosMoves: ; Evolutions db EV_ITEM, WATER_STONE, 1, STARMIE db 0 ; Learnset db 17, WATER_GUN db 22, HARDEN db 27, RECOVER db 37, MINIMIZE db 40, BUBBLEBEAM db 42, LIGHT_SCREEN db 47, FOCUS_ENERGY db 53, HYDRO_PUMP db 56, HYPER_BEAM db 60, ICE_BEAM db 0 BlastoiseEvosMoves: ; Evolutions db 0 ; Learnset db 39, CONFUSION db 45, AMNESIA db 54, BITE db 61, BARRAGE db 66, HEADBUTT db 70, HYDRO_PUMP db 0 PinsirEvosMoves: ; Evolutions db 0 ; Learnset db 9, LEER db 15, FOCUS_ENERGY db 20, DOUBLE_TEAM db 29, BIND db 35, SWORDS_DANCE db 42, GUILLOTINE db 0 TangelaEvosMoves: ; Evolutions db 0 ; Learnset db 12, ABSORB db 15, POISONPOWDER db 19, WITHDRAW db 24, SLEEP_POWDER db 28, SLAM db 36, GROWTH db 0 MissingNo1FEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo20EvosMoves: ; Evolutions db 0 ; Learnset db 0 GrowlitheEvosMoves: ; Evolutions db EV_ITEM, FIRE_STONE, 1, ARCANINE db 0 ; Learnset db 8, EMBER db 11, LEER db 13, TAKE_DOWN db 17, AGILITY db 22, FIRE_SPIN db 25, RAGE db 28, GROWTH db 32, FLAMETHROWER db 37, AMNESIA db 45, FIRE_BLAST db 0 OnixEvosMoves: ; Evolutions db 0 ; Learnset db 15, BIND db 19, ROCK_THROW db 25, RAGE db 33, SLAM db 43, EARTHQUAKE db 0 FearowEvosMoves: ; Evolutions db 0 ; Learnset db 21, EGG_BOMB db 25, WING_ATTACK db 29, MIRROR_MOVE db 34, SAND_ATTACK db 43, BIND db 0 PidgeyEvosMoves: ; Evolutions db EV_LEVEL, 18, PIDGEOTTO db 0 ; Learnset db 5, SAND_ATTACK db 12, PECK db 19, WHIRLWIND db 28, QUICK_ATTACK db 36, AGILITY db 44, MIRROR_MOVE db 0 SlowpokeEvosMoves: ; Evolutions db EV_LEVEL, 37, SLOWBRO db 0 ; Learnset db 10, DISABLE db 15, HEADBUTT db 19, GROWL db 23, WATER_GUN db 28, AMNESIA db 34, PSYCHIC_M db 0 KadabraEvosMoves: ; Evolutions ;db EV_TRADE, 1, ALAKAZAM db EV_LEVEL, 40, ALAKAZAM db 0 ; Learnset db 17, CONFUSION db 20, DISABLE db 27, PSYBEAM db 31, RECOVER db 38, KINESIS db 42, REFLECT db 0 GravelerEvosMoves: ; Evolutions ;db EV_TRADE, 1, GOLEM db EV_LEVEL, 50, GOLEM db 0 ; Learnset db 26, BARRIER db 31, SEISMIC_TOSS db 35, ROCK_SLIDE db 41, EARTHQUAKE db 44, SKULL_BASH db 48, DIZZY_PUNCH db 0 ChanseyEvosMoves: ; Evolutions db 0 ; Learnset db 20, SING db 26, SOFTBOILED db 31, MINIMIZE db 37, POUND db 40, LIGHT_SCREEN db 44, DOUBLE_EDGE db 0 MachokeEvosMoves: ; Evolutions ;db EV_TRADE, 1, MACHAMP db EV_LEVEL, 46, MACHAMP db 0 ; Learnset db 29, ROLLING_KICK db 33, BODY_SLAM db 36, VICEGRIP db 40, MEGA_PUNCH db 44, COUNTER db 0 MrMimeEvosMoves: ; Evolutions db 0 ; Learnset db 29, BARRIER db 33, LIGHT_SCREEN db 41, DOUBLESLAP db 49, MEDITATE db 57, SUBSTITUTE db 0 HitmonleeEvosMoves: ; Evolutions db 0 ; Learnset db 38, ROLLING_KICK db 41, JUMP_KICK db 46, FOCUS_ENERGY db 51, HI_JUMP_KICK db 56, MEGA_KICK db 0 HitmonchanEvosMoves: ; Evolutions db 0 ; Learnset db 38, FIRE_PUNCH db 41, ICE_PUNCH db 46, THUNDERPUNCH db 51, MEGA_PUNCH db 56, COUNTER db 0 ArbokEvosMoves: ; Evolutions db 0 ; Learnset db 24, QUICK_ATTACK db 30, SMOKESCREEN db 33, SUPER_FANG db 38, ACID db 45, TOXIC db 0 ParasectEvosMoves: ; Evolutions db 0 ; Learnset db 27, GROWTH db 32, POISONPOWDER db 39, SLUDGE db 44, BIDE db 50, FURY_ATTACK db 0 PsyduckEvosMoves: ; Evolutions db EV_LEVEL, 33, GOLDUCK db 0 ; Learnset db 19, TAIL_WHIP db 24, AMNESIA db 31, CONFUSION db 35, DISABLE db 43, HYDRO_PUMP db 0 DrowzeeEvosMoves: ; Evolutions db EV_LEVEL, 36, HYPNO db 0 ; Learnset db 26, DISABLE db 29, CONFUSION db 31, HEADBUTT db 33, POISON_GAS db 39, MEDITATE ;db 37, MEDITATE db 0 GolemEvosMoves: ; Evolutions db 0 ; Learnset db 51, TAKE_DOWN db 55, BODY_SLAM db 60, FISSURE db 67, SWORDS_DANCE ;db 36, EARTHQUAKE ;db 43, EXPLOSION db 0 MissingNo32EvosMoves: ; Evolutions db 0 ; Learnset db 0 MagmarEvosMoves: ; Evolutions db 0 ; Learnset db 32, SMOG db 36, CONFUSE_RAY db 39, FIRE_PUNCH db 43, SMOKESCREEN db 47, FISSURE db 54, FLAMETHROWER db 0 MissingNo34EvosMoves: ; Evolutions db 0 ; Learnset db 0 ElectabuzzEvosMoves: ; Evolutions db 0 ; Learnset db 45, THUNDER_WAVE db 48, SCREECH db 53, THUNDERPUNCH db 59, METRONOME db 64, THUNDER db 0 MagnetonEvosMoves: ; Evolutions db 0 ; Learnset db 44, BODY_SLAM db 48, DISABLE db 51, BIND db 55, KINESIS db 59, SWIFT db 64, THUNDER db 0 KoffingEvosMoves: ; Evolutions db EV_LEVEL, 40, WEEZING db 0 ; Learnset db 28, POISON_GAS db 34, SMOKESCREEN db 39, EXPLOSION db 45, NIGHT_SHADE db 50, TOXIC db 0 MissingNo38EvosMoves: ; Evolutions db 0 ; Learnset db 0 MankeyEvosMoves: ; Evolutions db EV_LEVEL, 38, PRIMEAPE db 0 ; Learnset db 15, KARATE_CHOP db 21, FURY_SWIPES db 27, FOCUS_ENERGY db 33, SEISMIC_TOSS db 40, THRASH db 0 SeelEvosMoves: ; Evolutions db EV_LEVEL, 34, DEWGONG db 0 ; Learnset db 28, SCREECH db 30, REST db 40, AURORA_BEAM db 50, TAKE_DOWN db 55, ICE_BEAM db 0 DiglettEvosMoves: ; Evolutions db EV_LEVEL, 26, DUGTRIO db 0 ; Learnset db 15, SAND_ATTACK db 19, MEDITATE db 24, BODY_SLAM db 31, SLASH db 40, EARTHQUAKE db 0 TaurosEvosMoves: ; Evolutions db 0 ; Learnset db 27, STOMP db 34, BARRIER db 41, HEADBUTT db 50, ROAR db 57, TAKE_DOWN db 0 MissingNo3DEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo3EEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo3FEvosMoves: ; Evolutions db 0 ; Learnset db 0 FarfetchdEvosMoves: ; Evolutions db 0 ; Learnset db 14, WHIRLWIND db 18, FURY_ATTACK db 23, SLASH db 31, DRILL_PECK db 39, SWORDS_DANCE db 0 VenonatEvosMoves: ; Evolutions db EV_LEVEL, 31, VENOMOTH db 0 ; Learnset db 13, POISONPOWDER db 18, LEECH_LIFE db 22, STUN_SPORE db 27, PSYBEAM db 34, SLEEP_POWDER db 40, PSYCHIC_M db 0 DragoniteEvosMoves: ; Evolutions db 0 ; Learnset db 60, THUNDER db 66, SKY_ATTACK db 72, HORN_DRILL ;db 45, DRAGON_RAGE ;db 60, HYPER_BEAM db 0 MissingNo43EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo44EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo45EvosMoves: ; Evolutions db 0 ; Learnset db 0 DoduoEvosMoves: ; Evolutions db EV_LEVEL, 41, DODRIO db 0 ; Learnset db 30, GROWL db 37, FURY_ATTACK db 40, DRILL_PECK db 44, RAGE db 50, TRI_ATTACK db 54, AGILITY db 0 PoliwagEvosMoves: ; Evolutions db EV_LEVEL, 25, POLIWHIRL db 0 ; Learnset db 16, HYPNOSIS db 22, WATER_GUN db 28, DOUBLESLAP ;db 31, BODY_SLAM ;db 38, AMNESIA ;db 45, HYDRO_PUMP db 0 JynxEvosMoves: ; Evolutions db 0 ; Learnset db 30, LICK db 36, DOUBLESLAP db 41, ICE_PUNCH db 49, BODY_SLAM db 56, THRASH db 65, BLIZZARD db 0 MoltresEvosMoves: ; Evolutions db 0 ; Learnset db 51, FIRE_BLAST db 55, AGILITY db 60, SKY_ATTACK db 0 ArticunoEvosMoves: ; Evolutions db 0 ; Learnset db 51, BLIZZARD db 55, AGILITY db 60, SKY_ATTACK db 0 ZapdosEvosMoves: ; Evolutions db 0 ; Learnset db 51, THUNDER db 55, AGILITY db 60, SKY_ATTACK db 0 DittoEvosMoves: ; Evolutions db 0 ; Learnset db 0 MeowthEvosMoves: ; Evolutions db EV_LEVEL, 28, PERSIAN db 0 ; Learnset db 7, SCRATCH db 12, BITE db 15, SCREECH db 19, FURY_SWIPES db 23, SLASH db 0 KrabbyEvosMoves: ; Evolutions db EV_LEVEL, 33, KINGLER db 0 ; Learnset db 20, HARDEN db 25, VICEGRIP db 26, STOMP db 30, SAND_ATTACK db 35, TAKE_DOWN db 0 MissingNo4FEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo50EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo51EvosMoves: ; Evolutions db 0 ; Learnset db 0 VulpixEvosMoves: ; Evolutions db EV_ITEM, FIRE_STONE, 1, NINETALES db 0 ; Learnset db 22, QUICK_ATTACK db 26, CONFUSE_RAY db 28, FIRE_SPIN db 30, GLARE db 33, SMOKESCREEN db 37, FLAMETHROWER db 40, LOW_KICK db 42, SUPER_FANG db 44, DOUBLE_TEAM db 47, FIRE_BLAST db 0 NinetalesEvosMoves: ; Evolutions db 0 ; Learnset db 0 PikachuEvosMoves: ; Evolutions db EV_ITEM, THUNDER_STONE, 1, RAICHU db 0 ; Learnset db 10, THUNDER_WAVE db 17, SWIFT db 20, QUICK_ATTACK db 23, SCREECH db 26, BODY_SLAM db 30, FURY_SWIPES db 33, AGILITY db 38, THUNDERBOLT db 43, THUNDER db 47, HYPER_BEAM db 0 RaichuEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo56EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo57EvosMoves: ; Evolutions db 0 ; Learnset db 0 DratiniEvosMoves: ; Evolutions db EV_LEVEL, 30, DRAGONAIR db 0 ; Learnset db 10, THUNDER_WAVE db 20, FOCUS_ENERGY db 29, SLAM db 35, DRAGON_RAGE db 41, HYPER_BEAM db 0 DragonairEvosMoves: ; Evolutions db EV_LEVEL, 55, DRAGONITE db 0 ; Learnset db 35, AGILITY db 40, DRAGON_RAGE db 43, RAZOR_WIND db 49, HYPER_BEAM db 57, THUNDER db 0 KabutoEvosMoves: ; Evolutions db EV_LEVEL, 55, KABUTOPS db 0 ; Learnset db 47, ABSORB db 51, WITHDRAW db 53, BARRIER db 59, HYDRO_PUMP db 0 KabutopsEvosMoves: ; Evolutions db 0 ; Learnset db 57, VICEGRIP db 60, SWORDS_DANCE db 63, ROCK_SLIDE db 66, HYDRO_PUMP db 0 HorseaEvosMoves: ; Evolutions db EV_LEVEL, 42, SEADRA db 0 ; Learnset db 29, SMOKESCREEN db 34, LEER db 40, WATER_GUN db 47, AGILITY db 55, HYDRO_PUMP db 0 SeadraEvosMoves: ; Evolutions db 0 ; Learnset db 45, CLAMP db 50, WATERFALL db 53, FOCUS_ENERGY db 59, AURORA_BEAM db 64, HYDRO_PUMP db 0 MissingNo5EEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo5FEvosMoves: ; Evolutions db 0 ; Learnset db 0 SandshrewEvosMoves: ; Evolutions db EV_LEVEL, 22, SANDSLASH db 0 ; Learnset db 12, SAND_ATTACK db 17, MINIMIZE db 20, HEADBUTT db 21, SWIFT db 25, FURY_SWIPES db 0 SandslashEvosMoves: ; Evolutions db 0 ; Learnset db 26, SPIKE_CANNON db 30, FURY_SWIPES db 33, SLASH db 38, DOUBLE_EDGE db 42, DIZZY_PUNCH db 0 OmanyteEvosMoves: ; Evolutions db EV_LEVEL, 55, OMASTAR db 0 ; Learnset db 47, FIRE_SPIN db 51, WITHDRAW db 53, WATER_GUN db 59, HYDRO_PUMP db 0 OmastarEvosMoves: ; Evolutions db 0 ; Learnset db 57, BIND db 60, SPIKE_CANNON db 63, DRILL_PECK db 66, HYDRO_PUMP db 0 JigglypuffEvosMoves: ; Evolutions db EV_ITEM, MOON_STONE, 1, WIGGLYTUFF db 0 ; Learnset db 9, POUND db 14, DEFENSE_CURL db 19, REST db 21, MIMIC db 24, DOUBLESLAP db 29, DISABLE db 32, SUBSTITUTE db 34, BODY_SLAM db 39, DOUBLE_EDGE db 43, METRONOME db 0 WigglytuffEvosMoves: ; Evolutions db 0 ; Learnset db 0 EeveeEvosMoves: ; Evolutions db EV_ITEM, FIRE_STONE, 1, FLAREON db EV_ITEM, THUNDER_STONE, 1, JOLTEON db EV_ITEM, WATER_STONE, 1, VAPOREON db 0 ; Learnset db 31, QUICK_ATTACK db 36, TAIL_WHIP db 42, BITE db 50, TAKE_DOWN db 0 FlareonEvosMoves: ; Evolutions db 0 ; Learnset db 31, EMBER db 36, TAIL_WHIP db 42, BITE db 45, TAKE_DOWN db 47, QUICK_ATTACK db 49, FLAMETHROWER db 53, RAGE db 59, FIRE_BLAST db 0 JolteonEvosMoves: ; Evolutions db 0 ; Learnset db 31, THUNDERSHOCK db 36, TAIL_WHIP db 42, BITE db 45, TAKE_DOWN db 47, DOUBLE_KICK db 49, THUNDERBOLT db 51, PIN_MISSILE db 59, THUNDER db 0 VaporeonEvosMoves: ; Evolutions db 0 ; Learnset db 31, WATER_GUN db 36, TAIL_WHIP db 42, BITE db 45, TAKE_DOWN db 47, HAZE db 49, WATERFALL db 51, MIST db 59, HYDRO_PUMP db 0 MachopEvosMoves: ; Evolutions db EV_LEVEL, 28, MACHOKE db 0 ; Learnset db 6, LEER db 11, LOW_KICK db 16, FOCUS_ENERGY db 20, SEISMIC_TOSS db 25, SUBMISSION db 0 ZubatEvosMoves: ; Evolutions db EV_LEVEL, 22, GOLBAT db 0 ; Learnset db 8, SONICBOOM db 12, BITE db 15, CONFUSE_RAY db 20, WING_ATTACK db 24, HAZE db 0 EkansEvosMoves: ; Evolutions db EV_LEVEL, 22, ARBOK db 0 ; Learnset db 10, POISON_STING db 14, BITE db 18, GLARE db 21, SCREECH db 27, ACID db 0 ParasEvosMoves: ; Evolutions db EV_LEVEL, 24, PARASECT db 0 ; Learnset db 9, STUN_SPORE db 13, LEECH_LIFE db 16, SPORE db 20, SLASH db 25, GROWTH db 0 PoliwhirlEvosMoves: ; Evolutions db EV_ITEM, WATER_STONE, 1, POLIWRATH db 0 ; Learnset db 27, BUBBLEBEAM db 30, CONFUSION db 32, AMNESIA db 36, DOUBLESLAP db 40, BODY_SLAM db 43, COUNTER db 47, MIMIC db 50, HI_JUMP_KICK db 54, HYDRO_PUMP db 58, PSYCHIC_M db 0 PoliwrathEvosMoves: ; Evolutions db 0 ; Learnset ;db 16, HYPNOSIS ;db 19, WATER_GUN db 0 WeedleEvosMoves: ; Evolutions db EV_LEVEL, 7, KAKUNA db 0 ; Learnset db 0 KakunaEvosMoves: ; Evolutions db EV_LEVEL, 10, BEEDRILL db 0 ; Learnset db 0 BeedrillEvosMoves: ; Evolutions db 0 ; Learnset db 12, FURY_ATTACK db 15, FOCUS_ENERGY db 17, TWINEEDLE db 19, RAGE db 23, PIN_MISSILE db 27, AGILITY db 33, AURORA_BEAM db 0 MissingNo73EvosMoves: ; Evolutions db 0 ; Learnset db 0 DodrioEvosMoves: ; Evolutions db 0 ; Learnset db 45, BARRAGE db 48, RAGE db 53, TRI_ATTACK db 56, AGILITY db 60, MIRROR_MOVE db 64, SCREECH db 0 PrimeapeEvosMoves: ; Evolutions db 0 ; Learnset db 40, SUBMISSION db 43, THRASH db 49, SEISMIC_TOSS db 54, SWORDS_DANCE db 60, HI_JUMP_KICK db 0 DugtrioEvosMoves: ; Evolutions db 0 ; Learnset db 28, ROCK_THROW db 33, SLASH db 39, BARRAGE db 45, EARTHQUAKE db 51, SKULL_BASH db 0 VenomothEvosMoves: ; Evolutions db 0 ; Learnset db 33, POISON_GAS db 38, REFLECT db 41, SLEEP_POWDER db 46, PSYCHIC_M db 50, HYPNOSIS db 55, SKY_ATTACK db 0 DewgongEvosMoves: ; Evolutions db 0 ; Learnset db 40, ROAR db 43, REST db 48, AURORA_BEAM db 51, TAKE_DOWN db 57, BLIZZARD db 0 MissingNo79EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo7AEvosMoves: ; Evolutions db 0 ; Learnset db 0 CaterpieEvosMoves: ; Evolutions db EV_LEVEL, 7, METAPOD db 0 ; Learnset db 0 MetapodEvosMoves: ; Evolutions db EV_LEVEL, 10, BUTTERFREE db 0 ; Learnset db 0 ButterfreeEvosMoves: ; Evolutions db 0 ; Learnset db 12, CONFUSION db 15, POISONPOWDER db 17, STUN_SPORE db 19, SLEEP_POWDER db 22, SUPERSONIC db 26, WHIRLWIND db 32, PSYBEAM db 0 MachampEvosMoves: ; Evolutions db 0 ; Learnset db 48, TRI_ATTACK db 52, FLAMETHROWER db 56, HI_JUMP_KICK db 60, MEGA_KICK ;db 52, SUBMISSION db 0 MissingNo7FEvosMoves: ; Evolutions db 0 ; Learnset db 0 GolduckEvosMoves: ; Evolutions db 0 ; Learnset db 34, PSYWAVE db 38, BUBBLEBEAM db 43, SONICBOOM db 48, HYDRO_PUMP db 56, PSYCHIC_M db 0 HypnoEvosMoves: ; Evolutions db 0 ; Learnset db 37, DREAM_EATER db 40, DOUBLESLAP db 44, MEDITATE db 49, HI_JUMP_KICK db 54, PSYCHIC_M db 61, TELEPORT db 0 GolbatEvosMoves: ; Evolutions db 0 ; Learnset db 25, SCREECH db 29, HAZE db 33, GUST db 37, ROAR db 43, BODY_SLAM db 0 MewtwoEvosMoves: ; Evolutions db 0 ; Learnset ;db 63, BARRIER ;db 66, PSYCHIC_M ;db 70, RECOVER db 75, MIST db 81, AMNESIA db 0 SnorlaxEvosMoves: ; Evolutions db 0 ; Learnset db 35, BODY_SLAM db 41, BARRIER db 48, DOUBLE_EDGE db 56, HYPER_BEAM db 0 MagikarpEvosMoves: ; Evolutions db EV_LEVEL, 20, GYARADOS db 0 ; Learnset db 15, TACKLE db 0 MissingNo86EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNo87EvosMoves: ; Evolutions db 0 ; Learnset db 0 MukEvosMoves: ; Evolutions db 0 ; Learnset db 40, TOXIC db 43, ACID_ARMOR db 47, SUBMISSION db 55, RAGE db 58, FOCUS_ENERGY db 65, MIMIC db 0 MissingNo8AEvosMoves: ; Evolutions db 0 ; Learnset db 0 KinglerEvosMoves: ; Evolutions db 0 ; Learnset db 38, BUBBLEBEAM db 42, TAKE_DOWN db 46, CLAMP db 49, ROLLING_KICK db 54, GUILLOTINE db 0 CloysterEvosMoves: ; Evolutions db 0 ; Learnset ;db 50, SPIKE_CANNON db 0 MissingNo8CEvosMoves: ; Evolutions db 0 ; Learnset db 0 ElectrodeEvosMoves: ; Evolutions db 0 ; Learnset db 35, QUICK_ATTACK db 40, SMOKESCREEN db 44, HEADBUTT db 50, THUNDERBOLT db 60, THUNDER db 0 ClefableEvosMoves: ; Evolutions db 0 ; Learnset db 0 WeezingEvosMoves: ; Evolutions db 0 ; Learnset db 42, SLUDGE db 49, EXPLOSION db 53, NIGHT_SHADE db 59, TOXIC db 63, LOVELY_KISS db 0 PersianEvosMoves: ; Evolutions db 0 ; Learnset db 30, MINIMIZE db 35, QUICK_ATTACK db 37, RAGE db 42, SING db 48, METRONOME db 0 MarowakEvosMoves: ; Evolutions db 0 ; Learnset db 39, AGILITY db 45, BONEMERANG db 51, TAKE_DOWN db 58, SUBMISSION db 65, NIGHT_SHADE db 0 MissingNo92EvosMoves: ; Evolutions db 0 ; Learnset db 0 HaunterEvosMoves: ; Evolutions ;db EV_TRADE, 1, GENGAR db EV_LEVEL, 45, GENGAR db 0 ; Learnset db 29, HYPNOSIS db 38, DREAM_EATER db 0 AbraEvosMoves: ; Evolutions db EV_LEVEL, 16, KADABRA db 0 ; Learnset db 0 AlakazamEvosMoves: ; Evolutions db 0 ; Learnset db 44, REFLECT db 48, MIMIC db 51, SUBSTITUTE db 55, PSYCHIC_M ;db 38, PSYCHIC_M ;db 42, REFLECT db 0 PidgeottoEvosMoves: ; Evolutions db EV_LEVEL, 36, PIDGEOT db 0 ; Learnset db 19, BIDE db 23, QUICK_ATTACK db 28, WHIRLWIND db 34, DRILL_PECK db 40, MIRROR_MOVE db 49, SKY_ATTACK db 0 PidgeotEvosMoves: ; Evolutions db 0 ; Learnset db 37, MIRROR_MOVE db 44, SCREECH db 50, MINIMIZE db 56, SKY_ATTACK db 62, RAGE db 68, SKY_ATTACK db 0 StarmieEvosMoves: ; Evolutions db 0 ; Learnset db 0 BulbasaurEvosMoves: ; Evolutions db EV_LEVEL, 16, IVYSAUR db 0 ; Learnset db 7, LEECH_SEED db 13, VINE_WHIP db 20, POISONPOWDER db 27, MEGA_DRAIN db 34, SLEEP_POWDER db 41, SOLARBEAM ;db 48, GROWTH db 0 VenusaurEvosMoves: ; Evolutions db 0 ; Learnset db 37, GROWTH db 43, RAZOR_LEAF db 49, POISONPOWDER db 56, COUNTER db 60, MEGA_DRAIN db 68, SOLARBEAM ;db 85, HYPER_BEAM db 0 TentacruelEvosMoves: ; Evolutions db 0 ; Learnset db 42, SCREECH db 45, MIST db 55, DISABLE db 65, HYDRO_PUMP db 70, TOXIC db 75, MEGA_DRAIN ;db 43, SCREECH ;db 50, HYDRO_PUMP db 0 MissingNo9CEvosMoves: ; Evolutions db 0 ; Learnset db 0 GoldeenEvosMoves: ; Evolutions db EV_LEVEL, 38, SEAKING db 0 ; Learnset db 24, SUPERSONIC db 29, HORN_ATTACK db 33, FURY_ATTACK db 37, WATERFALL db 40, AGILITY db 45, HORN_DRILL db 0 SeakingEvosMoves: ; Evolutions db 0 ; Learnset db 40, WATER_GUN db 44, TAKE_DOWN db 48, AGILITY db 51, HORN_DRILL db 55, LOVELY_KISS db 60, HYPER_BEAM db 0 MissingNo9FEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNoA0EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNoA1EvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNoA2EvosMoves: ; Evolutions db 0 ; Learnset db 0 PonytaEvosMoves: ; Evolutions db EV_LEVEL, 40, RAPIDASH db 0 ; Learnset db 25, GROWL db 28, STOMP db 32, SWIFT db 36, FIRE_SPIN db 41, TAKE_DOWN db 47, AGILITY db 0 RapidashEvosMoves: ; Evolutions db 0 ; Learnset db 42, QUICK_ATTACK db 45, SCREECH db 49, JUMP_KICK db 51, FLAMETHROWER db 55, FIRE_BLAST ;db 55, AGILITY db 0 RattataEvosMoves: ; Evolutions db EV_LEVEL, 20, RATICATE db 0 ; Learnset db 7, QUICK_ATTACK db 14, HYPER_FANG db 23, FOCUS_ENERGY db 34, SUPER_FANG db 0 RaticateEvosMoves: ; Evolutions db 0 ; Learnset db 22, FURY_SWIPES db 25, FOCUS_ENERGY db 31, MINIMIZE db 36, SUPER_FANG db 41, BODY_SLAM db 0 NidorinoEvosMoves: ; Evolutions db EV_ITEM, MOON_STONE, 1, NIDOKING db 0 ; Learnset db 17, HORN_ATTACK db 22, HYPER_FANG db 26, FURY_ATTACK db 31, FOCUS_ENERGY db 36, TOXIC db 40, THRASH db 43, LOW_KICK db 49, HORN_DRILL db 52, SEISMIC_TOSS db 58, DOUBLE_KICK db 0 NidorinaEvosMoves: ; Evolutions db EV_ITEM, MOON_STONE, 1, NIDOQUEEN db 0 ; Learnset db 17, QUICK_ATTACK db 22, HYPER_FANG db 26, TAKE_DOWN db 31, BIDE db 36, SLUDGE db 40, BITE db 43, LOW_KICK db 49, VICEGRIP db 52, SEISMIC_TOSS db 58, DOUBLE_KICK db 0 GeodudeEvosMoves: ; Evolutions db EV_LEVEL, 25, GRAVELER db 0 ; Learnset db 11, DEFENSE_CURL db 16, ROCK_THROW db 21, EXPLOSION db 26, ROCK_SLIDE db 31, EARTHQUAKE db 36, MEGA_PUNCH db 0 PorygonEvosMoves: ; Evolutions db 0 ; Learnset db 32, TRI_ATTACK db 35, NIGHT_SHADE db 39, MIMIC db 43, PSYCHIC_M db 0 AerodactylEvosMoves: ; Evolutions db 0 ; Learnset db 48, TAKE_DOWN db 53, SUPER_FANG db 60, HYPER_BEAM db 69, SKY_ATTACK db 0 MissingNoACEvosMoves: ; Evolutions db 0 ; Learnset db 0 MagnemiteEvosMoves: ; Evolutions db EV_LEVEL, 40, MAGNETON db 0 ; Learnset db 23, SONICBOOM db 28, THUNDERSHOCK db 34, SUPERSONIC db 39, SWIFT db 46, KINESIS db 52, BIND db 0 MissingNoAEEvosMoves: ; Evolutions db 0 ; Learnset db 0 MissingNoAFEvosMoves: ; Evolutions db 0 ; Learnset db 0 CharmanderEvosMoves: ; Evolutions db EV_LEVEL, 16, CHARMELEON db 0 ; Learnset db 9, EMBER db 15, FIRE_SPIN db 22, RAGE db 30, SLASH db 38, FLAMETHROWER db 46, FIRE_BLAST db 0 SquirtleEvosMoves: ; Evolutions db EV_LEVEL, 16, WARTORTLE db 0 ; Learnset db 8, BUBBLE db 15, BUBBLEBEAM db 22, BITE db 28, HEADBUTT db 35, WITHDRAW db 42, HYDRO_PUMP db 0 CharmeleonEvosMoves: ; Evolutions db EV_LEVEL, 36, CHARIZARD db 0 ; Learnset db 18, CONVERSION db 25, ROCK_THROW db 34, FIRE_PUNCH db 40, FIRE_BLAST db 45, SLASH db 57, FLAMETHROWER db 0 WartortleEvosMoves: ; Evolutions db EV_LEVEL, 36, BLASTOISE db 0 ; Learnset db 18, ACID_ARMOR db 25, WATER_GUN db 32, MIST db 38, HYDRO_PUMP db 43, HEADBUTT db 55, WITHDRAW db 0 CharizardEvosMoves: ; Evolutions db 0 ; Learnset db 39, DOUBLE_EDGE db 47, WHIRLWIND db 56, RAGE db 63, DRAGON_RAGE db 68, SLASH db 72, FIRE_BLAST db 0 MissingNoB5EvosMoves: ; Evolutions db 0 ; Learnset db 0 FossilKabutopsEvosMoves: ; Evolutions db 0 ; Learnset db 0 FossilAerodactylEvosMoves: ; Evolutions db 0 ; Learnset db 0 MonGhostEvosMoves: ; Evolutions db 0 ; Learnset db 0 OddishEvosMoves: ; Evolutions db EV_LEVEL, 21, GLOOM db 0 ; Learnset db 7, POISONPOWDER db 12, STUN_SPORE db 15, GROWTH ;db 18, ACID ;db 20, PETAL_DANCE ;db 25, SOLARBEAM db 0 GloomEvosMoves: ; Evolutions db EV_ITEM, LEAF_STONE, 1, VILEPLUME db 0 ; Learnset db 23, ACID db 26, LEECH_SEED db 28, HAZE db 30, TOXIC db 34, PETAL_DANCE db 37, WITHDRAW db 41, SLEEP_POWDER db 44, NIGHT_SHADE db 48, SPORE db 50, SOLARBEAM db 0 VileplumeEvosMoves: ; Evolutions db 0 ; Learnset ;db 15, POISONPOWDER ;db 17, STUN_SPORE ;db 19, SLEEP_POWDER db 0 BellsproutEvosMoves: ; Evolutions db EV_LEVEL, 21, WEEPINBELL db 0 ; Learnset db 13, WRAP db 15, POISONPOWDER db 18, GROWTH ;db 21, STUN_SPORE ;db 26, ACID ;db 33, RAZOR_LEAF ;db 42, SLAM db 0 WeepinbellEvosMoves: ; Evolutions db EV_ITEM, LEAF_STONE, 1, VICTREEBEL db 0 ; Learnset db 23, ACID db 25, STUN_SPORE db 28, RAZOR_LEAF db 30, VINE_WHIP db 33, SUPERSONIC db 37, SLEEP_POWDER db 39, SONICBOOM db 44, WITHDRAW db 48, METRONOME db 52, SOLARBEAM db 0 VictreebelEvosMoves: ; Evolutions db 0 ; Learnset ;db 13, WRAP ;db 15, POISONPOWDER ;db 18, SLEEP_POWDER db 0
; A153264: Numbers n such that 16*n+15 is not prime. ; Submitted by Christian Krause ; 0,3,5,6,8,9,10,12,15,17,18,19,20,21,24,25,27,30,31,32,33,34,35,36,38,39,40,41,42,43,45,47,48,49,50,51,52,54,55,57,58,59,60,62,63,65,66,69,70,72,73,74,75,77,78,80,81,83,84,85,86,87,90,93,94,95,96,99,100,101,102,104,105,106,107,108,110,111,112,114,115,117,118,119,120,122,123,125,126,127,129,130,132,134,135,136,138,140,141,143 mov $1,6 mov $2,$0 add $2,2 pow $2,2 lpb $2 add $1,8 sub $2,1 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. add $0,$3 sub $0,1 add $1,8 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 lpe mov $0,$1 sub $0,22 div $0,16
; A161418: Number of triangles in the Y-toothpick structure after n rounds. ; 0,0,0,0,6,6,12,12,24,30 sub $0,1 mov $1,$0 sub $2,$0 mul $0,4 add $2,7 add $1,$2 div $0,$1 mod $2,2 trn $0,$2 mul $0,6
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; ReadEs.Asm ; ; Abstract: ; ; AsmReadEs function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; UINT16 ; EFIAPI ; AsmReadEs ( ; VOID ; ); ;------------------------------------------------------------------------------ global ASM_PFX(AsmReadEs) ASM_PFX(AsmReadEs): mov eax, es ret
musicChan2MainMenuTheme:: setRegisters $00, $00, $00, $00 .loop: setVolume $A5 disableTerminals TERMINAL_TWO wait SEMIBREVE * 8 enableTerminals TERMINAL_TWO repeat 2 setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_G * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_G * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_G * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait MINIM disableTerminals TERMINAL_TWO wait MINIM enableTerminals TERMINAL_TWO setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_B * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_E * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_B * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_E * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_B * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_E * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait MINIM disableTerminals TERMINAL_TWO wait MINIM enableTerminals TERMINAL_TWO setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_G * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_G * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait CROTCHET setFrequency NOTE_G * 2, $80 wait CROTCHET setFrequency NOTE_F * 2, $80 wait MINIM disableTerminals TERMINAL_TWO wait MINIM enableTerminals TERMINAL_TWO setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_B * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_E * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET disableTerminals TERMINAL_TWO wait CROTCHET enableTerminals TERMINAL_TWO setFrequency NOTE_D * 2, $80 wait CROTCHET disableTerminals TERMINAL_TWO wait CROTCHET enableTerminals TERMINAL_TWO setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_B * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait CROTCHET setFrequency NOTE_E * 2, $80 wait CROTCHET setFrequency NOTE_D * 2, $80 wait MINIM disableTerminals TERMINAL_TWO wait MINIM enableTerminals TERMINAL_TWO continue repeat 3 setFrequency NOTE_E * 2, $80 wait SEMIBREVE setFrequency NOTE_D * 2, $80 wait SEMIBREVE setFrequency NOTE_C * 2, $80 wait SEMIBREVE setFrequency NOTE_D * 2, $80 wait MINIM disableTerminals TERMINAL_TWO wait MINIM enableTerminals TERMINAL_TWO continue setFrequency NOTE_C * 2, $80 wait SEMIBREVE setFrequency NOTE_B * 2, $80 wait SEMIBREVE setFrequency NOTE_A * 2, $80 wait SEMIBREVE setFrequency NOTE_G, $80 wait SEMIBREVE stopMusic jump .loop
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmRescaler.h" #include <limits> #include <algorithm> // std::max #include <stdlib.h> // abort #include <string.h> // memcpy #include <math.h> // floor namespace gdcm { // parameter 'size' is in bytes template <typename TOut, typename TIn> void RescaleFunction(TOut *out, const TIn *in, double intercept, double slope, size_t size) { size /= sizeof(TIn); for(size_t i = 0; i != size; ++i) { // Implementation detail: // The rescale function does not add the usual +0.5 to do the proper integer type // cast, since TOut is expected to be floating point type whenever it would occur out[i] = (TOut)(slope * in[i] + intercept); //assert( out[i] == (TOut)(slope * in[i] + intercept) ); // will really slow down stuff... //assert( in[i] == (TIn)(((double)out[i] - intercept) / slope + 0.5) ); // For image such as: gdcmData/MR16BitsAllocated_8BitsStored.dcm, the following line will not work: // Indeed the pixel declares itself as 16/8/7 with pixel representation of 1. In this case // anything outside the range [-127,128] is required to be discarded ! //assert( (TIn)out[i] == in[i] ); } } // no such thing as partial specialization of function in c++ // so instead use this trick: template<typename TOut, typename TIn> struct FImpl; template<typename TOut, typename TIn> void InverseRescaleFunction(TOut *out, const TIn *in, double intercept, double slope, size_t size) { FImpl<TOut,TIn>::InverseRescaleFunction(out,in,intercept,slope,size); } // users, don't touch this! template<typename TOut, typename TIn> struct FImpl { // parameter 'size' is in bytes // TODO: add template parameter for intercept/slope so that we can have specialized instantiation // when 1. both are int, 2. slope is 1, 3. intercept is 0 // Detail: casting from float to int is soooo slow static void InverseRescaleFunction( TOut *out, const TIn *in, double intercept, double slope, size_t size) // users, go ahead and specialize this { // If you read the code down below you'll see a specialized function for float, thus // if we reach here it pretty much means slope/intercept were integer type assert( intercept == (int)intercept ); assert( slope == (int)slope ); size /= sizeof(TIn); for(size_t i = 0; i != size; ++i) { // '+ 0.5' trick is NOT needed for image such as: gdcmData/D_CLUNIE_CT1_J2KI.dcm out[i] = (TOut)(((double)in[i] - intercept) / slope ); } } }; template < typename T > static inline T round(const double d) { return (T)floor(d + 0.5); } template<typename TOut> struct FImpl<TOut, float> { static void InverseRescaleFunction(TOut *out, const float *in, double intercept, double slope, size_t size) { size /= sizeof(float); for(size_t i = 0; i != size; ++i) { // '+ 0.5' trick is needed for instance for : gdcmData/MR-MONO2-12-shoulder.dcm // well known trick of adding 0.5 after a floating point type operation to properly find the // closest integer that will represent the transformation // TOut in this case is integer type, while input is floating point type out[i] = round<TOut>(((double)in[i] - intercept) / slope); //assert( out[i] == (TOut)(((double)in[i] - intercept) / slope ) ); } } }; template<typename TOut> struct FImpl<TOut, double> { static void InverseRescaleFunction(TOut *out, const double *in, double intercept, double slope, size_t size) { size /= sizeof(double); for(size_t i = 0; i != size; ++i) { // '+ 0.5' trick is needed for instance for : gdcmData/MR-MONO2-12-shoulder.dcm // well known trick of adding 0.5 after a floating point type operation to properly find the // closest integer that will represent the transformation // TOut in this case is integer type, while input is floating point type out[i] = round<TOut>(((double)in[i] - intercept) / slope); //assert( out[i] == (TOut)(((double)in[i] - intercept) / slope ) ); } } }; static inline PixelFormat::ScalarType ComputeBestFit(const PixelFormat &pf, double intercept, double slope) { PixelFormat::ScalarType st = PixelFormat::UNKNOWN; assert( slope == (int)slope && intercept == (int)intercept); const double min = slope * (double)pf.GetMin() + intercept; const double max = slope * (double)pf.GetMax() + intercept; assert( min <= max ); assert( min == (int64_t)min && max == (int64_t)max ); if( min >= 0 ) // unsigned { if( max <= std::numeric_limits<uint8_t>::max() ) { st = PixelFormat::UINT8; } else if( max <= std::numeric_limits<uint16_t>::max() ) { st = PixelFormat::UINT16; } else if( max <= std::numeric_limits<uint32_t>::max() ) { st = PixelFormat::UINT32; } else { gdcmErrorMacro( "Unhandled Pixel Format" ); return st; } } else { if( max <= std::numeric_limits<int8_t>::max() && min >= std::numeric_limits<int8_t>::min() ) { st = PixelFormat::INT8; } else if( max <= std::numeric_limits<int16_t>::max() && min >= std::numeric_limits<int16_t>::min() ) { st = PixelFormat::INT16; } else if( max <= std::numeric_limits<int32_t>::max() && min >= std::numeric_limits<int32_t>::min() ) { st = PixelFormat::INT32; } else { gdcmErrorMacro( "Unhandled Pixel Format" ); return st; } } // postcondition: assert( min >= PixelFormat(st).GetMin() ); assert( max <= PixelFormat(st).GetMax() ); assert( st != PixelFormat::UNKNOWN ); return st; } PixelFormat::ScalarType Rescaler::ComputeInterceptSlopePixelType() { assert( PF != PixelFormat::UNKNOWN ); PixelFormat::ScalarType output = PixelFormat::UNKNOWN; if( PF == PixelFormat::SINGLEBIT ) return PixelFormat::SINGLEBIT; if( Slope != (int)Slope || Intercept != (int)Intercept) { //assert( PF != PixelFormat::INT8 && PF != PixelFormat::UINT8 ); // Is there any Object that have Rescale on char ? assert( PF != PixelFormat::SINGLEBIT ); return PixelFormat::FLOAT64; } //if( PF.IsValid() ) { const double intercept = Intercept; const double slope = Slope; output = ComputeBestFit (PF,intercept,slope); } return output; } template <typename TIn> void Rescaler::RescaleFunctionIntoBestFit(char *out, const TIn *in, size_t n) { double intercept = Intercept; double slope = Slope; PixelFormat::ScalarType output = ComputeInterceptSlopePixelType(); if( UseTargetPixelType ) { output = TargetScalarType; } switch(output) { case PixelFormat::SINGLEBIT: assert(0); break; case PixelFormat::UINT8: RescaleFunction<uint8_t,TIn>((uint8_t*)out,in,intercept,slope,n); break; case PixelFormat::INT8: RescaleFunction<int8_t,TIn>((int8_t*)out,in,intercept,slope,n); break; case PixelFormat::UINT16: RescaleFunction<uint16_t,TIn>((uint16_t*)out,in,intercept,slope,n); break; case PixelFormat::INT16: RescaleFunction<int16_t,TIn>((int16_t*)out,in,intercept,slope,n); break; case PixelFormat::UINT32: RescaleFunction<uint32_t,TIn>((uint32_t*)out,in,intercept,slope,n); break; case PixelFormat::INT32: RescaleFunction<int32_t,TIn>((int32_t*)out,in,intercept,slope,n); break; case PixelFormat::FLOAT32: RescaleFunction<float,TIn>((float*)out,in,intercept,slope,n); break; case PixelFormat::FLOAT64: RescaleFunction<double,TIn>((double*)out,in,intercept,slope,n); break; default: assert(0); break; } } template <typename TIn> void Rescaler::InverseRescaleFunctionIntoBestFit(char *out, const TIn *in, size_t n) { const double intercept = Intercept; const double slope = Slope; PixelFormat output = ComputePixelTypeFromMinMax(); switch(output) { case PixelFormat::SINGLEBIT: assert(0); break; case PixelFormat::UINT8: InverseRescaleFunction<uint8_t,TIn>((uint8_t*)out,in,intercept,slope,n); break; case PixelFormat::INT8: InverseRescaleFunction<int8_t,TIn>((int8_t*)out,in,intercept,slope,n); break; case PixelFormat::UINT16: InverseRescaleFunction<uint16_t,TIn>((uint16_t*)out,in,intercept,slope,n); break; case PixelFormat::INT16: InverseRescaleFunction<int16_t,TIn>((int16_t*)out,in,intercept,slope,n); break; case PixelFormat::UINT32: InverseRescaleFunction<uint32_t,TIn>((uint32_t*)out,in,intercept,slope,n); break; case PixelFormat::INT32: InverseRescaleFunction<int32_t,TIn>((int32_t*)out,in,intercept,slope,n); break; default: assert(0); break; } } bool Rescaler::InverseRescale(char *out, const char *in, size_t n) { bool fastpath = true; switch(PF) { case PixelFormat::FLOAT32: case PixelFormat::FLOAT64: fastpath = false; break; default: ; } // fast path: if( fastpath && (Slope == 1 && Intercept == 0) ) { memcpy(out,in,n); return true; } // check if we are dealing with floating point type if( Slope != (int)Slope || Intercept != (int)Intercept) { // need to rescale as double (64bits) as slope/intercept are 64bits //assert(0); } // else integral type switch(PF) { case PixelFormat::UINT16: InverseRescaleFunctionIntoBestFit<uint16_t>(out,(uint16_t*)in,n); break; case PixelFormat::INT16: InverseRescaleFunctionIntoBestFit<int16_t>(out,(int16_t*)in,n); break; case PixelFormat::UINT32: InverseRescaleFunctionIntoBestFit<uint32_t>(out,(uint32_t*)in,n); break; case PixelFormat::INT32: InverseRescaleFunctionIntoBestFit<int32_t>(out,(int32_t*)in,n); break; case PixelFormat::FLOAT32: assert( sizeof(float) == 32 / 8 ); InverseRescaleFunctionIntoBestFit<float>(out,(float*)in,n); break; case PixelFormat::FLOAT64: assert( sizeof(double) == 64 / 8 ); InverseRescaleFunctionIntoBestFit<double>(out,(double*)in,n); break; default: assert(0); break; } return true; } bool Rescaler::Rescale(char *out, const char *in, size_t n) { if( UseTargetPixelType == false ) { // fast path: if( Slope == 1 && Intercept == 0 ) { memcpy(out,in,n); return true; } // check if we are dealing with floating point type if( Slope != (int)Slope || Intercept != (int)Intercept) { // need to rescale as float (32bits) as slope/intercept are 32bits } } // else integral type switch(PF) { case PixelFormat::SINGLEBIT: memcpy(out,in,n); break; case PixelFormat::UINT8: RescaleFunctionIntoBestFit<uint8_t>(out,(uint8_t*)in,n); break; case PixelFormat::INT8: RescaleFunctionIntoBestFit<int8_t>(out,(int8_t*)in,n); break; case PixelFormat::UINT12: case PixelFormat::UINT16: RescaleFunctionIntoBestFit<uint16_t>(out,(uint16_t*)in,n); break; case PixelFormat::INT12: case PixelFormat::INT16: RescaleFunctionIntoBestFit<int16_t>(out,(int16_t*)in,n); break; case PixelFormat::UINT32: RescaleFunctionIntoBestFit<uint32_t>(out,(uint32_t*)in,n); break; case PixelFormat::INT32: RescaleFunctionIntoBestFit<int32_t>(out,(int32_t*)in,n); break; default: gdcmErrorMacro( "Unhandled: " << PF ); assert(0); break; } return true; } PixelFormat ComputeInverseBestFitFromMinMax(/*const PixelFormat &pf,*/ double intercept, double slope, double _min, double _max) { PixelFormat st = PixelFormat::UNKNOWN; //assert( slope == (int)slope && intercept == (int)intercept); double dmin = (_min - intercept ) / slope; double dmax = (_max - intercept ) / slope; assert( dmin <= dmax ); assert( dmax <= std::numeric_limits<int64_t>::max() ); assert( dmin >= std::numeric_limits<int64_t>::min() ); /* * Tricky: what happen in the case where floating point approximate dmax as: 65535.000244081035 * Take for instance: _max = 64527, intercept = -1024, slope = 1.000244140625 * => dmax = 65535.000244081035 * thus we must always make sure to cast to an integer first. */ int64_t min = (int64_t)dmin; int64_t max = (int64_t)dmax; int log2max = 0; if( min >= 0 ) // unsigned { if( max <= std::numeric_limits<uint8_t>::max() ) { st = PixelFormat::UINT8; } else if( max <= std::numeric_limits<uint16_t>::max() ) { st = PixelFormat::UINT16; } else if( max <= std::numeric_limits<uint32_t>::max() ) { st = PixelFormat::UINT32; } else { assert(0); } int64_t max2 = max; // make a copy while (max2 >>= 1) ++log2max; // need + 1 in case max == 4095 => 12bits stored required st.SetBitsStored( (unsigned short)(log2max + 1) ); } else { if( max <= std::numeric_limits<int8_t>::max() && min >= std::numeric_limits<int8_t>::min() ) { st = PixelFormat::INT8; } else if( max <= std::numeric_limits<int16_t>::max() && min >= std::numeric_limits<int16_t>::min() ) { st = PixelFormat::INT16; } else if( max <= std::numeric_limits<int32_t>::max() && min >= std::numeric_limits<int32_t>::min() ) { st = PixelFormat::INT32; } else { assert(0); } assert( min < 0 ); #if 0 int log2min = 0; int64_t min2 = -min; // make a copy int64_t max2 = max; // make a copy while (min2 >>= 1) ++log2min; while (max2 >>= 1) ++log2max; const int64_t bs = std::max( log2min, log2max ) + 1 + 1 /* 2 complement */; #else int64_t max2 = max - min; // make a copy while (max2 >>= 1) ++log2max; const int64_t bs = log2max + 1; #endif assert( bs <= st.GetBitsAllocated() ); st.SetBitsStored( (unsigned short)bs ); } // postcondition: assert( min >= PixelFormat(st).GetMin() ); assert( max <= PixelFormat(st).GetMax() ); assert( st != PixelFormat::UNKNOWN ); assert( st != PixelFormat::FLOAT32 && st != PixelFormat::FLOAT16 && st != PixelFormat::FLOAT64 ); return st; } PixelFormat Rescaler::ComputePixelTypeFromMinMax() { assert( PF != PixelFormat::UNKNOWN ); const double intercept = Intercept; const double slope = Slope; const PixelFormat output = ComputeInverseBestFitFromMinMax (/*PF,*/intercept,slope,ScalarRangeMin,ScalarRangeMax); assert( output != PixelFormat::UNKNOWN && output >= PixelFormat::UINT8 && output <= PixelFormat::INT32 ); return output; } void Rescaler::SetTargetPixelType( PixelFormat const & targetpf ) { TargetScalarType = targetpf.GetScalarType(); } void Rescaler::SetUseTargetPixelType(bool b) { UseTargetPixelType = b; } } // end namespace gdcm
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <iomanip> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; const double EPS = 1e-9; const int INF = 0x7f7f7f7f; const double PI=acos(-1.0); #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define rep(i,n) for(int i = 1 ; i<=(n) ; i++) #define repI(i,n) for(int i = 0 ; i<(n) ; i++) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define iseq(a,b) (fabs(a-b)<EPS) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long #define POPCOUNT __builtin_popcount #define POPCOUNTLL __builtin_popcountll #define RIGHTMOST __builtin_ctzll #define LEFTMOST(x) (63-__builtin_clzll((x))) #define sf scanf #define pf printf #define FMT(...) (sprintf(CRTBUFF, __VA_ARGS__)?CRTBUFF:0) char CRTBUFF[30000]; template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #define dipta00 #ifdef dipta007 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(args...) /// Just strip off all debug tokens #define trace(...) ///yeeeee #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; ///****************** template ends here **************** // g++ -g -O2 -std=gnu++11 A.cpp // ./a.out #define MAX 100004 int arr[MAX]; int tree[MAX*4]; void init(int node,int b,int e) { if(b==e) { tree[node]=arr[b]; return; } int Left= node << 1; int Right= (node << 1) +1; int mid=(b+e)>>1; init(Left,b,mid); init(Right,mid+1,e); tree[node]=tree[Left]+tree[Right]; } int query(int node,int b,int e,int i,int j) { if (i > e || j < b) return 0; if (b >= i && e <= j) return tree[node]; int Left=node<<1; int Right=(node<<1)+1; int mid=(b+e)>>1; int p1=query(Left,b,mid,i,j); int p2=query(Right,mid+1,e,i,j); return p1+p2; } void update(int node,int b,int e,int i,int newvalue) { if (i > e || i < b) return; if (b >= i && e <= i) { tree[node]=newvalue; return; } int Left=node<<1; int Right=(node<<1)+1; int mid=(b+e)>>1; update(Left,b,mid,i,newvalue); update(Right,mid+1,e,i,newvalue); tree[node]=tree[Left]+tree[Right]; } int main() { #ifdef dipta007 //READ("in.txt"); //WRITE("out.txt"); #endif // dipta007 // ios_base::sync_with_stdio(0);cin.tie(0); int n, m; while(~getII(n, m)) { FOR(i,0,n-1) getI(arr[i]); vector < pii > vp; FOR(i, 1, m) { int x,y; getII(x,y); vp.PB(MP(x,y)); } ans[i] } return 0; }
; Include smsspec .include "../dist/smsspec.asm" ; Include the files to test .include "incrementer.asm" ; Define mocks .ramsection "mock instances" slot 2 smsspec.mocks.start: db RandomGenerator.generateByte instanceof smsspec.mock smsspec.mocks.end: db .ends ; Define an smsspec.suite label, which smsspec will call .section "smsspec.suite" free smsspec.suite: ; Include your test suite files .include "incrementer.spec.asm" ; End of test suite ret .ends
;;;;;;;;;;;;;;;;;;;;;;;;;;;; %macro PRINTF32 1-* pushf pushad jmp %%endstr %%str: db %1 %%endstr: %rep %0 - 1 %rotate -1 push dword %1 %endrep push %%str call printf add esp, 4*%0 popad popf %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.size 8000 .text@48 ei jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 44 ld b, 90 lbegin_waitvblank: ldff a, (c) cmp a, b jrnz lbegin_waitvblank xor a, a ldff(40), a ld hl, 9f00 ld b, 20 lbegin_clearvram: dec l ld(hl), a jrnz lbegin_clearvram dec h dec b jrnz lbegin_clearvram ld hl, 8010 ld a, ff ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld hl, 9f00 ld b, 04 ld a, 01 lbegin_filluppertilemap: dec l ld(hl), a jrnz lbegin_filluppertilemap dec h dec b jrnz lbegin_filluppertilemap ld a, e4 ldff(47), a ld a, ff ldff(48), a ld a, 80 ldff(68), a ld a, ff ld c, 69 ldff(c), a ldff(c), a ld a, aa ldff(c), a ldff(c), a ld a, 55 ldff(c), a ldff(c), a xor a, a ldff(c), a ldff(c), a ld a, 80 ldff(6a), a ld a, 00 ld c, 6b ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a ld hl, fea0 xor a, a lbegin_fill_oam: dec l ld(hl), a jrnz lbegin_fill_oam ld a, 10 ld(hl), a inc l ld a, 09 ld(hl), a ld a, 97 ldff(40), a ld c, 41 ld b, 03 lbegin_waitm3: ldff a, (c) and a, b cmp a, b jrnz lbegin_waitm3 ld a, 20 ldff(c), a ld a, 02 ldff(ff), a xor a, a ldff(0f), a ei .text@1000 lstatint: nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop ld a, 9f ldff(40), a pop hl .text@1028 ld a, 97 ldff(40), a
/******************************************************************************* * * MIT License * * Copyright 2019-2020 Advanced Micro Devices, Inc. * * 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 <Tensile/ArithmeticUnitTypes.hpp> #include <Tensile/Utils.hpp> #include <algorithm> namespace Tensile { std::map<ArithmeticUnit, ArithmeticUnitTypeInfo> ArithmeticUnitTypeInfo::data; std::map<std::string, ArithmeticUnit> ArithmeticUnitTypeInfo::typeNames; std::string ToString(ArithmeticUnit d) { switch(d) { case ArithmeticUnit::Any: return "Any"; case ArithmeticUnit::MFMA: return "MFMA"; case ArithmeticUnit::VALU: return "VALU"; case ArithmeticUnit::Count: default:; } return "Invalid"; } template <ArithmeticUnit T> void ArithmeticUnitTypeInfo::registerTypeInfo() { using T_Info = ArithmeticUnitInfo<T>; ArithmeticUnitTypeInfo info; info.m_arithmeticUnit = T_Info::Enum; info.name = T_Info::Name(); addInfoObject(info); } void ArithmeticUnitTypeInfo::registerAllTypeInfo() { registerTypeInfo<ArithmeticUnit::Any>(); registerTypeInfo<ArithmeticUnit::MFMA>(); registerTypeInfo<ArithmeticUnit::VALU>(); } void ArithmeticUnitTypeInfo::registerAllTypeInfoOnce() { static int call_once = (registerAllTypeInfo(), 0); } void ArithmeticUnitTypeInfo::addInfoObject(ArithmeticUnitTypeInfo const& info) { auto toLower = [](std::string tmp) { std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); return tmp; }; data[info.m_arithmeticUnit] = info; // Add some flexibility to names registry. Accept // lower case versions of the strings typeNames[info.name] = info.m_arithmeticUnit; typeNames[toLower(info.name)] = info.m_arithmeticUnit; } ArithmeticUnitTypeInfo const& ArithmeticUnitTypeInfo::Get(int index) { return Get(static_cast<ArithmeticUnit>(index)); } ArithmeticUnitTypeInfo const& ArithmeticUnitTypeInfo::Get(ArithmeticUnit t) { registerAllTypeInfoOnce(); auto iter = data.find(t); if(iter == data.end()) throw std::runtime_error(concatenate("Invalid arithmetic unit: ", static_cast<int>(t))); return iter->second; } ArithmeticUnitTypeInfo const& ArithmeticUnitTypeInfo::Get(std::string const& str) { registerAllTypeInfoOnce(); auto iter = typeNames.find(str); if(iter == typeNames.end()) throw std::runtime_error(concatenate("Invalid arithmetic unit: ", str)); return Get(iter->second); } std::ostream& operator<<(std::ostream& stream, const ArithmeticUnit& t) { return stream << ToString(t); } std::istream& operator>>(std::istream& stream, ArithmeticUnit& t) { std::string strValue; stream >> strValue; t = ArithmeticUnitTypeInfo::Get(strValue).m_arithmeticUnit; return stream; } } // namespace Tensile
; A116701: Number of permutations of length n that avoid the patterns 132, 4321. ; 1,2,5,13,31,66,127,225,373,586,881,1277,1795,2458,3291,4321,5577,7090,8893,11021,13511,16402,19735,23553,27901,32826,38377,44605,51563,59306,67891,77377,87825,99298,111861,125581,140527,156770,174383,193441 mov $1,$0 mul $1,$0 mov $2,$0 add $0,$1 add $1,6 add $1,$2 div $1,2 sub $1,$2 mul $0,$1 mov $1,$0 div $1,6 add $1,1
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ui/webui/chromeos/internet_config_dialog.h" #include "chrome/browser/ui/webui/chromeos/internet_detail_dialog.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_type_pattern.h" #include "components/onc/onc_constants.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace { // JS API callbacks names. const char kJsApiLaunchInternetDetailDialog[] = "launchInternetDetailDialog"; const char kJsApiLaunchAddWiFiNetworkDialog[] = "launchAddWiFiNetworkDialog"; const char kJsApiShowNetworkConfig[] = "showNetworkConfig"; const char kJsApiShowNetworkDetails[] = "showNetworkDetails"; } // namespace namespace chromeos { NetworkDropdownHandler::NetworkDropdownHandler( JSCallsContainer* js_calls_container) : BaseWebUIHandler(js_calls_container) {} NetworkDropdownHandler::~NetworkDropdownHandler() = default; void NetworkDropdownHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) {} void NetworkDropdownHandler::Initialize() {} void NetworkDropdownHandler::RegisterMessages() { AddCallback(kJsApiLaunchInternetDetailDialog, &NetworkDropdownHandler::HandleLaunchInternetDetailDialog); AddCallback(kJsApiLaunchAddWiFiNetworkDialog, &NetworkDropdownHandler::HandleLaunchAddWiFiNetworkDialog); AddRawCallback(kJsApiShowNetworkDetails, &NetworkDropdownHandler::HandleShowNetworkDetails); AddRawCallback(kJsApiShowNetworkConfig, &NetworkDropdownHandler::HandleShowNetworkConfig); } void NetworkDropdownHandler::HandleLaunchInternetDetailDialog() { // Empty string opens the internet detail dialog for the default network. InternetDetailDialog::ShowDialog( "", LoginDisplayHost::default_host()->GetNativeWindow()); } void NetworkDropdownHandler::HandleLaunchAddWiFiNetworkDialog() { // Make sure WiFi is enabled. NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler(); if (handler->GetTechnologyState(NetworkTypePattern::WiFi()) != NetworkStateHandler::TECHNOLOGY_ENABLED) { handler->SetTechnologyEnabled(NetworkTypePattern::WiFi(), true, network_handler::ErrorCallback()); } chromeos::InternetConfigDialog::ShowDialogForNetworkType( ::onc::network_type::kWiFi, LoginDisplayHost::default_host()->GetNativeWindow()); } void NetworkDropdownHandler::HandleShowNetworkDetails( const base::ListValue* args) { DCHECK_GE(args->GetList().size(), 2U); std::string type = args->GetList()[0].GetString(); std::string guid = args->GetList()[1].GetString(); if (type == ::onc::network_type::kCellular) { // Make sure Cellular is enabled. NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler(); if (handler->GetTechnologyState(NetworkTypePattern::Cellular()) != NetworkStateHandler::TECHNOLOGY_ENABLED) { handler->SetTechnologyEnabled(NetworkTypePattern::Cellular(), true, network_handler::ErrorCallback()); } } InternetDetailDialog::ShowDialog( guid, LoginDisplayHost::default_host()->GetNativeWindow()); } void NetworkDropdownHandler::HandleShowNetworkConfig( const base::ListValue* args) { DCHECK(!args->GetList().empty()); std::string guid = args->GetList()[0].GetString(); chromeos::InternetConfigDialog::ShowDialogForNetworkId( guid, LoginDisplayHost::default_host()->GetNativeWindow()); } } // namespace chromeos
#include "QtGui/QBrush/qbrush_wrap.h" #include "Extras/Utils/nutils.h" #include "QtCore/QVariant/qvariant_wrap.h" #include "QtGui/QColor/qcolor_wrap.h" #include "QtGui/QPixmap/qpixmap_wrap.h" Napi::FunctionReference QBrushWrap::constructor; Napi::Object QBrushWrap::init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); char CLASSNAME[] = "QBrush"; Napi::Function func = DefineClass( env, CLASSNAME, {InstanceMethod("isOpaque", &QBrushWrap::isOpaque), InstanceMethod("setColor", &QBrushWrap::setColor), InstanceMethod("color", &QBrushWrap::color), InstanceMethod("setStyle", &QBrushWrap::setStyle), InstanceMethod("style", &QBrushWrap::style), InstanceMethod("setTexture", &QBrushWrap::setTexture), InstanceMethod("texture", &QBrushWrap::texture), StaticMethod("fromQVariant", &StaticQBrushWrapMethods::fromQVariant), COMPONENT_WRAPPED_METHODS_EXPORT_DEFINE(QBrushWrap)}); constructor = Napi::Persistent(func); exports.Set(CLASSNAME, func); return exports; } QBrushWrap::QBrushWrap(const Napi::CallbackInfo& info) : Napi::ObjectWrap<QBrushWrap>(info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); if (info.Length() == 2) { if (info[0].IsNumber()) { Qt::GlobalColor color = (Qt::GlobalColor)info[0].As<Napi::Number>().Int32Value(); Qt::BrushStyle style = (Qt::BrushStyle)info[1].As<Napi::Number>().Int32Value(); this->instance = std::make_unique<QBrush>(color, style); } else { Napi::Object colorObject = info[0].As<Napi::Object>(); QColorWrap* colorWrap = Napi::ObjectWrap<QColorWrap>::Unwrap(colorObject); Qt::BrushStyle style = (Qt::BrushStyle)info[1].As<Napi::Number>().Int32Value(); this->instance = std::make_unique<QBrush>(*colorWrap->getInternalInstance(), style); } } else if (info.Length() == 1) { this->instance = std::unique_ptr<QBrush>(info[0].As<Napi::External<QBrush>>().Data()); } else if (info.Length() == 0) { this->instance = std::make_unique<QBrush>(); } else { Napi::TypeError::New(env, "Wrong number of arguments") .ThrowAsJavaScriptException(); } this->rawData = extrautils::configureComponent(this->getInternalInstance()); } QBrushWrap::~QBrushWrap() { this->instance.reset(); } QBrush* QBrushWrap::getInternalInstance() { return this->instance.get(); } Napi::Value QBrushWrap::isOpaque(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); return Napi::Boolean::New(env, this->instance->isOpaque()); } Napi::Value QBrushWrap::setColor(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); if (info[0].IsNumber()) { Qt::GlobalColor color = (Qt::GlobalColor)info[0].As<Napi::Number>().Int32Value(); this->instance->setColor(color); } else { Napi::Object colorObject = info[0].As<Napi::Object>(); QColorWrap* colorWrap = Napi::ObjectWrap<QColorWrap>::Unwrap(colorObject); this->instance->setColor(*colorWrap->getInternalInstance()); } return env.Null(); } Napi::Value QBrushWrap::color(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); QColor color = this->instance->color(); auto instance = QColorWrap::constructor.New( {Napi::External<QColor>::New(env, new QColor(color))}); return instance; } Napi::Value QBrushWrap::setStyle(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); Qt::BrushStyle style = (Qt::BrushStyle)info[0].As<Napi::Number>().Int32Value(); this->instance->setStyle(style); return env.Null(); } Napi::Value QBrushWrap::style(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); Qt::BrushStyle style = this->instance->style(); return Napi::Number::New(env, static_cast<int>(style)); } Napi::Value QBrushWrap::setTexture(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); Napi::Object pixmapObject = info[0].As<Napi::Object>(); QPixmapWrap* pixmapWrap = Napi::ObjectWrap<QPixmapWrap>::Unwrap(pixmapObject); this->instance->setTexture(*pixmapWrap->getInternalInstance()); return env.Null(); } Napi::Value QBrushWrap::texture(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); QPixmap pixmap = this->instance->texture(); auto instance = QPixmapWrap::constructor.New( {Napi::External<QPixmap>::New(env, new QPixmap(pixmap))}); return instance; } Napi::Value StaticQBrushWrapMethods::fromQVariant( const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); Napi::Object variantObject = info[0].As<Napi::Object>(); QVariantWrap* variantWrap = Napi::ObjectWrap<QVariantWrap>::Unwrap(variantObject); QVariant* variant = variantWrap->getInternalInstance(); QBrush brush = variant->value<QBrush>(); auto instance = QBrushWrap::constructor.New( {Napi::External<QBrush>::New(env, new QBrush(brush))}); return instance; }
; A227071: Let s(m) = the set of k > 0 such that k^m ends with k. Then a(n) = least m such that s(m) = s(n). ; 1,2,3,2,5,6,3,2,9,2,11,2,5,2,3,6,17,2,3,2,21,2,3,2,9,26,3,2,5,2,11,2,33,2,3,6,5,2,3,2,41,2,3,2,5,6,3,2,17,2,51,2,5,2,3,6,9,2,3,2,21,2,3,2,65,6,3,2,5,2,11,2,9,2,3,26,5,2,3,2,81,2,3,2,5,6,3,2,9,2,11,2,5,2,3,6,33,2,3,2 gcd $0,12089258196146291747061760000000000000000000000000000000000000000 mod $0,12089258196146291747061760000000000000000000000000000000000000000 add $0,1
// Copyright (c) 2017-2018 The NextON developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privacydialog.h" #include "ui_privacydialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "libzerocoin/Denominations.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "coincontrol.h" #include "zpivcontroldialog.h" #include "spork.h" #include "askpassphrasedialog.h" #include <QClipboard> #include <QSettings> #include <utilmoneystr.h> #include <QtWidgets> #include <primitives/deterministicmint.h> #include <accumulators.h> PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowCloseButtonHint), ui(new Ui::PrivacyDialog), walletModel(0), currentBalance(-1) { nDisplayUnit = 0; // just make sure it's not unitialized ui->setupUi(this); // "Spending 999999 zPIV ought to be enough for anybody." - Bill Gates, 2017 ui->zPIVpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) ); ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) ); // Default texts for (mini-) coincontrol ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); ui->labelzPIVSyncStatus->setText("(" + tr("out of sync") + ")"); // Sunken frame for minting messages ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui->TEMintStatus->setLineWidth (2); ui->TEMintStatus->setMidLineWidth (2); ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Coin Control signals connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); // Denomination labels ui->labelzDenom1Text->setText(tr("Denom. with value <b>1</b>:")); ui->labelzDenom2Text->setText(tr("Denom. with value <b>5</b>:")); ui->labelzDenom3Text->setText(tr("Denom. with value <b>10</b>:")); ui->labelzDenom4Text->setText(tr("Denom. with value <b>50</b>:")); ui->labelzDenom5Text->setText(tr("Denom. with value <b>100</b>:")); ui->labelzDenom6Text->setText(tr("Denom. with value <b>500</b>:")); ui->labelzDenom7Text->setText(tr("Denom. with value <b>1000</b>:")); ui->labelzDenom8Text->setText(tr("Denom. with value <b>5000</b>:")); // AutoMint status ui->label_AutoMintStatus->setText(tr("AutoMint Status:")); // Global Supply labels ui->labelZsupplyText1->setText(tr("Denom. <b>1</b>:")); ui->labelZsupplyText5->setText(tr("Denom. <b>5</b>:")); ui->labelZsupplyText10->setText(tr("Denom. <b>10</b>:")); ui->labelZsupplyText50->setText(tr("Denom. <b>50</b>:")); ui->labelZsupplyText100->setText(tr("Denom. <b>100</b>:")); ui->labelZsupplyText500->setText(tr("Denom. <b>500</b>:")); ui->labelZsupplyText1000->setText(tr("Denom. <b>1000</b>:")); ui->labelZsupplyText5000->setText(tr("Denom. <b>5000</b>:")); // NextON settings QSettings settings; if (!settings.contains("nSecurityLevel")){ nSecurityLevel = 42; settings.setValue("nSecurityLevel", nSecurityLevel); } else{ nSecurityLevel = settings.value("nSecurityLevel").toInt(); } if (!settings.contains("fMinimizeChange")){ fMinimizeChange = false; settings.setValue("fMinimizeChange", fMinimizeChange); } else{ fMinimizeChange = settings.value("fMinimizeChange").toBool(); } ui->checkBoxMinimizeChange->setChecked(fMinimizeChange); // Start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // Hide those placeholder elements needed for CoinControl interaction ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator ui->dummyHideWidget->hide(); // Dummy widget with elements to hide // Set labels/buttons depending on SPORK_16 status updateSPORK16Status(); } PrivacyDialog::~PrivacyDialog() { delete ui; } void PrivacyDialog::setModel(WalletModel* walletModel) { this->walletModel = walletModel; if (walletModel && walletModel->getOptionsModel()) { // Keep up to date with wallet setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(walletModel->getOptionsModel(), SIGNAL(zeromintEnableChanged(bool)), this, SLOT(updateAutomintStatus())); connect(walletModel->getOptionsModel(), SIGNAL(zeromintPercentageChanged(int)), this, SLOT(updateAutomintStatus())); ui->securityLevel->setValue(nSecurityLevel); } } void PrivacyDialog::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void PrivacyDialog::on_addressBookButton_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(walletModel->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->zPIVpayAmount->setFocus(); } } void PrivacyDialog::on_pushButtonMintzPIV_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zPIV is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Reset message text ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Mint_zPIV, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first.")); return; } } QString sAmount = ui->labelMintAmountValue->text(); CAmount nAmount = sAmount.toInt() * COIN; // Minting amount must be > 0 if(nAmount <= 0){ ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0.")); return; } ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zPIV..."); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); CWalletTx wtx; vector<CDeterministicMint> vMints; string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); // Return if something went wrong during minting if (strError != ""){ ui->TEMintStatus->setPlainText(QString::fromStdString(strError)); return; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; // Minting successfully finished. Show some stats for entertainment. QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zPIV in ") + QString::number(fDuration) + tr(" sec. Used denominations:\n"); // Clear amount to avoid double spending when accidentally clicking twice ui->labelMintAmountValue->setText ("0"); QString strStats = ""; ui->TEMintStatus->setPlainText(strStatsHeader); for (CDeterministicMint dMint : vMints) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); strStats = strStats + QString::number(dMint.GetDenomination()) + " "; ui->TEMintStatus->setPlainText(strStatsHeader + strStats); ui->TEMintStatus->repaint (); } ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text // Available balance isn't always updated, so force it. setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); coinControlUpdateLabels(); return; } void PrivacyDialog::on_pushButtonMintReset_clicked() { ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware.\nPlease be patient...")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetMintResult = pwalletMain->ResetMintZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text return; } void PrivacyDialog::on_pushButtonSpentReset_clicked() { ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: ")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text return; } void PrivacyDialog::on_pushButtonSpendzPIV_clicked() { if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zPIV is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Send_zPIV, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled return; } // Wallet is unlocked now, sedn zPIV sendzPIV(); return; } // Wallet already unlocked or not encrypted at all, send zPIV sendzPIV(); } void PrivacyDialog::on_pushButtonZPivControl_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ZPivControlDialog* zPivControl = new ZPivControlDialog(this); zPivControl->setModel(walletModel); zPivControl->exec(); } void PrivacyDialog::setZPivControlLabels(int64_t nAmount, int nQuantity) { ui->labelzPivSelected_int->setText(QString::number(nAmount)); ui->labelQuantitySelected_int->setText(QString::number(nQuantity)); } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } void PrivacyDialog::sendzPIV() { QSettings settings; // Handle 'Pay To' address options CBitcoinAddress address(ui->payTo->text().toStdString()); if(ui->payTo->text().isEmpty()){ QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok); } else{ if (!address.IsValid()) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid NextON Address"), QMessageBox::Ok, QMessageBox::Ok); ui->payTo->setFocus(); return; } } // Double is allowed now double dAmount = ui->zPIVpayAmount->text().toDouble(); CAmount nAmount = roundint64(dAmount* COIN); // Check amount validity if (!MoneyRange(nAmount) || nAmount <= 0.0) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok); ui->zPIVpayAmount->setFocus(); return; } // Convert change to zPIV bool fMintChange = ui->checkBoxMintChange->isChecked(); // Persist minimize change setting fMinimizeChange = ui->checkBoxMinimizeChange->isChecked(); settings.setValue("fMinimizeChange", fMinimizeChange); // Warn for additional fees if amount is not an integer and change as zPIV is requested bool fWholeNumber = floor(dAmount) == dAmount; double dzFee = 0.0; if(!fWholeNumber) dzFee = 1.0 - (dAmount - floor(dAmount)); if(!fWholeNumber && fMintChange){ QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>"; strFeeWarning += QString::number(dzFee, 'f', 8) + " PIV </b>will be added to the standard transaction fees!<br />"; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"), strFeeWarning, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled ui->zPIVpayAmount->setFocus(); return; } } // Persist Security Level for next start nSecurityLevel = ui->securityLevel->value(); settings.setValue("nSecurityLevel", nSecurityLevel); // Spend confirmation message box // Add address info if available QString strAddressLabel = ""; if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){ strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") "; } // General info QString strQuestionString = tr("Are you sure you want to send?<br /><br />"); QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zPIV</b>"; QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />"; if(ui->payTo->text().isEmpty()){ // No address provided => send to local address strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />"); } QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?"; strQuestionString += strAmount + strAddress + strSecurityLevel; // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), strQuestionString, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled return; } int64_t nTime = GetTimeMillis(); ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware.\nPlease be patient...")); ui->TEMintStatus->repaint(); // use mints from zPIV selector if applicable vector<CMintMeta> vMintsToFetch; vector<CZerocoinMint> vMintsSelected; if (!ZPivControlDialog::setSelectedMints.empty()) { vMintsToFetch = ZPivControlDialog::GetSelectedMints(); for (auto& meta : vMintsToFetch) { if (meta.nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION) { //version 1 coins have to use full security level to successfully spend. if (nSecurityLevel < 100) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Version 1 zPIV require a security level of 100 to successfully spend."), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Failed to spend zPIV")); ui->TEMintStatus->repaint(); return; } } CZerocoinMint mint; if (!pwalletMain->GetMint(meta.hashSerial, mint)) { ui->TEMintStatus->setPlainText(tr("Failed to fetch mint associated with serial hash")); ui->TEMintStatus->repaint(); return; } vMintsSelected.emplace_back(mint); } } // Spend zPIV CWalletTx wtxNew; CZerocoinSpendReceipt receipt; bool fSuccess = false; if(ui->payTo->text().isEmpty()){ // Spend to newly generated local address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange); } else { // Spend to supplied destination address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address); } // Display errors during spend if (!fSuccess) { if (receipt.GetStatus() == ZPIV_SPEND_V1_SEC_LEVEL) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Version 1 zPIV require a security level of 100 to successfully spend."), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Failed to spend zPIV")); ui->TEMintStatus->repaint(); return; } int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zPIV transaction if (nNeededSpends > nMaxSpends) { QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed.\nMaximum allowed: ") + QString::number(nMaxSpends, 10); strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend."); QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString())); } else { QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage())); } ui->zPIVpayAmount->setFocus(); ui->TEMintStatus->repaint(); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text return; } if (walletModel && walletModel->getAddressTableModel()) { // If zPIV was spent successfully update the addressbook with the label std::string labelText = ui->addAsLabel->text().toStdString(); if (!labelText.empty()) walletModel->updateAddressBookLabels(address.Get(), labelText, "send"); else walletModel->updateAddressBookLabels(address.Get(), "(no label)", "send"); } // Clear zpiv selector in case it was used ZPivControlDialog::setSelectedMints.clear(); ui->labelzPivSelected_int->setText(QString("0")); ui->labelQuantitySelected_int->setText(QString("0")); // Some statistics for entertainment QString strStats = ""; CAmount nValueIn = 0; int nCount = 0; for (CZerocoinSpend spend : receipt.GetSpends()) { strStats += tr("zPIV Spend #: ") + QString::number(nCount) + ", "; strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", "; strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n"; strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n"; nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination()); ++nCount; } CAmount nValueOut = 0; for (const CTxOut& txout: wtxNew.vout) { strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " Piv, "; nValueOut += txout.nValue; strStats += tr("address: "); CTxDestination dest; if(txout.scriptPubKey.IsZerocoinMint()) strStats += tr("zPIV Mint"); else if(ExtractDestination(txout.scriptPubKey, dest)) strStats += tr(CBitcoinAddress(dest).ToString().c_str()); strStats += "\n"; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"); strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n"; QString strReturn; strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n"; strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n"; strReturn += strStats; // Clear amount to avoid double spending when accidentally clicking twice ui->zPIVpayAmount->setText ("0"); ui->TEMintStatus->setPlainText(strReturn); ui->TEMintStatus->repaint(); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text } void PrivacyDialog::on_payTo_textChanged(const QString& address) { updateLabel(address); } // Coin Control: copy label "Quantity" to clipboard void PrivacyDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void PrivacyDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: button inputs -> show actual coin control dialog void PrivacyDialog::coinControlButtonClicked() { if (!walletModel || !walletModel->getOptionsModel()) return; CoinControlDialog dlg; dlg.setModel(walletModel); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: update labels void PrivacyDialog::coinControlUpdateLabels() { if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); if (CoinControlDialog::coinControl->HasSelected()) { // Actual coin control calculation CoinControlDialog::updateLabels(walletModel, this); } else { ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); } } bool PrivacyDialog::updateLabel(const QString& address) { if (!walletModel) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; } void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentZerocoinBalance = zerocoinBalance; currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance; currentImmatureZerocoinBalance = immatureZerocoinBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances; std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; std::map<libzerocoin::CoinDenomination, int> mapImmature; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapDenomBalances.insert(make_pair(denom, 0)); mapUnconfirmed.insert(make_pair(denom, 0)); mapImmature.insert(make_pair(denom, 0)); } std::vector<CMintMeta> vMints = pwalletMain->zpivTracker->GetMints(false); map<libzerocoin::CoinDenomination, int> mapMaturityHeights = GetMintMaturityHeight(); for (auto& meta : vMints){ // All denominations mapDenomBalances.at(meta.denom)++; if (!meta.nHeight || chainActive.Height() - meta.nHeight <= Params().Zerocoin_MintRequiredConfirmations()) { // All unconfirmed denominations mapUnconfirmed.at(meta.denom)++; } else { if (meta.denom == libzerocoin::CoinDenomination::ZQ_ERROR) { mapImmature.at(meta.denom)++; } else if (meta.nHeight >= mapMaturityHeights.at(meta.denom)) { mapImmature.at(meta.denom)++; } } } int64_t nCoins = 0; int64_t nSumPerCoin = 0; int64_t nUnconfirmed = 0; int64_t nImmature = 0; QString strDenomStats, strUnconfirmed = ""; for (const auto& denom : libzerocoin::zerocoinDenomList) { nCoins = libzerocoin::ZerocoinDenominationToInt(denom); nSumPerCoin = nCoins * mapDenomBalances.at(denom); nUnconfirmed = mapUnconfirmed.at(denom); nImmature = mapImmature.at(denom); strUnconfirmed = ""; if (nUnconfirmed) { strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. "); } if(nImmature) { strUnconfirmed += QString::number(nImmature) + QString(" immature "); } if(nImmature || nUnconfirmed) { strUnconfirmed = QString("( ") + strUnconfirmed + QString(") "); } strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " + QString::number(nCoins) + " = <b>" + QString::number(nSumPerCoin) + " zPIV </b>"; switch (nCoins) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelzDenom1Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelzDenom2Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelzDenom3Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelzDenom4Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelzDenom5Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelzDenom6Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelzDenom7Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelzDenom8Amount->setText(strDenomStats); break; default: // Error Case: don't update display break; } } CAmount matureZerocoinBalance = zerocoinBalance - unconfirmedZerocoinBalance - immatureZerocoinBalance; CAmount nLockedBalance = 0; if (walletModel) { nLockedBalance = walletModel->getLockedBalance(); } ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zPIV ")); ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zPIV ")); ui->labelzPIVAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways)); // Display AutoMint status updateAutomintStatus(); // Update/enable labels and buttons depending on the current SPORK_16 status updateSPORK16Status(); // Display global supply ui->labelZsupplyAmount->setText(QString::number(chainActive.Tip()->GetZerocoinSupply()/COIN) + QString(" <b>zPIV </b> ")); for (auto denom : libzerocoin::zerocoinDenomList) { int64_t nSupply = chainActive.Tip()->mapZerocoinSupply.at(denom); QString strSupply = QString::number(nSupply) + " x " + QString::number(denom) + " = <b>" + QString::number(nSupply*denom) + " zPIV </b> "; switch (denom) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelZsupplyAmount1->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelZsupplyAmount5->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelZsupplyAmount10->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelZsupplyAmount50->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelZsupplyAmount100->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelZsupplyAmount500->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelZsupplyAmount1000->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelZsupplyAmount5000->setText(strSupply); break; default: // Error Case: don't update display break; } } } void PrivacyDialog::updateDisplayUnit() { if (walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if (currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); } } void PrivacyDialog::showOutOfSyncWarning(bool fShow) { ui->labelzPIVSyncStatus->setVisible(fShow); } void PrivacyDialog::keyPressEvent(QKeyEvent* event) { if (event->key() != Qt::Key_Escape) // press esc -> ignore { this->QDialog::keyPressEvent(event); } else { event->ignore(); } } void PrivacyDialog::updateAutomintStatus() { QString strAutomintStatus = tr("AutoMint Status:"); if (pwalletMain->isZeromintEnabled ()) { strAutomintStatus += tr(" <b>enabled</b>."); } else { strAutomintStatus += tr(" <b>disabled</b>."); } strAutomintStatus += tr(" Configured target percentage: <b>") + QString::number(pwalletMain->getZeromintPercentage()) + "%</b>"; ui->label_AutoMintStatus->setText(strAutomintStatus); } void PrivacyDialog::updateSPORK16Status() { // Update/enable labels, buttons and tooltips depending on the current SPORK_16 status bool fButtonsEnabled = ui->pushButtonMintzPIV->isEnabled(); bool fMaintenanceMode = GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE); if (fMaintenanceMode && fButtonsEnabled) { // Mint zPIV ui->pushButtonMintzPIV->setEnabled(false); ui->pushButtonMintzPIV->setToolTip(tr("zPIV is currently disabled due to maintenance.")); // Spend zPIV ui->pushButtonSpendzPIV->setEnabled(false); ui->pushButtonSpendzPIV->setToolTip(tr("zPIV is currently disabled due to maintenance.")); } else if (!fMaintenanceMode && !fButtonsEnabled) { // Mint zPIV ui->pushButtonMintzPIV->setEnabled(true); ui->pushButtonMintzPIV->setToolTip(tr("PrivacyDialog", "Enter an amount of PIV to convert to zPIV", 0)); // Spend zPIV ui->pushButtonSpendzPIV->setEnabled(true); ui->pushButtonSpendzPIV->setToolTip(tr("Spend Zerocoin. Without 'Pay To:' address creates payments to yourself.")); } }
; A052481: a(n) = 2^n*(binomial(n,2) + 1). ; 1,2,8,32,112,352,1024,2816,7424,18944,47104,114688,274432,647168,1507328,3473408,7929856,17956864,40370176,90177536,200278016,442499072,973078528,2130706432,4647288832,10099884032,21877489664,47244640256,101737037824,218506461184,468151435264,1000727379968,2134598746112,4544075399168,9655086481408,20478404067328,43361989820416,91671781965824,193514046488576,407918813904896,858718581293056,1805398092808192,3791116092571648,7951668092076032,16659800184061952,34867712740032512,72902018968059904 mov $1,$0 bin $0,2 mov $2,$1 lpb $2 mul $0,2 add $0,1 sub $2,1 lpe add $0,1
// Copyright (c) 2017, SUMOKOIN // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder 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 HOLDER 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. // // Parts of this file are originally copyright (c) 2014-2017, The Monero Project // Parts of this file are originally copyright (c) 2012-2013, The Cryptonote developers #pragma once #include <inttypes.h> #include <stddef.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <boost/align/aligned_alloc.hpp> #include "cuckaroo/cuckaroo29s.h" #if defined(_WIN32) || defined(_WIN64) #include <malloc.h> #include <intrin.h> #define HAS_WIN_INTRIN_API #endif // Note HAS_INTEL_HW and future HAS_ARM_HW only mean we can emit the AES instructions // check CPU support for the hardware AES encryption has to be done at runtime #if defined(__x86_64__) || defined(__i386__) || defined(_M_X86) || defined(_M_X64) #ifdef __GNUC__ #include <x86intrin.h> #pragma GCC target ("aes") #if !defined(HAS_WIN_INTRIN_API) #include <cpuid.h> #endif // !defined(HAS_WIN_INTRIN_API) #endif // __GNUC__ #define HAS_INTEL_HW #endif #ifdef HAS_INTEL_HW inline void cpuid(uint32_t eax, int32_t ecx, int32_t val[4]) { val[0] = 0; val[1] = 0; val[2] = 0; val[3] = 0; #if defined(HAS_WIN_INTRIN_API) __cpuidex(val, eax, ecx); #else __cpuid_count(eax, ecx, val[0], val[1], val[2], val[3]); #endif } inline bool hw_check_aes() { int32_t cpu_info[4]; cpuid(1, 0, cpu_info); return (cpu_info[2] & (1 << 25)) != 0; } #endif #ifdef HAS_ARM_HW inline bool hw_check_aes() { return false; } #endif #if !defined(HAS_INTEL_HW) && !defined(HAS_ARM_HW) inline bool hw_check_aes() { return false; } #endif // This cruft avoids casting-galore and allows us not to worry about sizeof(void*) class cn_sptr { public: cn_sptr() : base_ptr(nullptr) {} cn_sptr(uint64_t* ptr) { base_ptr = ptr; } cn_sptr(uint32_t* ptr) { base_ptr = ptr; } cn_sptr(uint8_t* ptr) { base_ptr = ptr; } #ifdef HAS_INTEL_HW cn_sptr(__m128i* ptr) { base_ptr = ptr; } #endif inline void set(void* ptr) { base_ptr = ptr; } inline cn_sptr offset(size_t i) { return reinterpret_cast<uint8_t*>(base_ptr)+i; } inline const cn_sptr offset(size_t i) const { return reinterpret_cast<uint8_t*>(base_ptr)+i; } inline void* as_void() { return base_ptr; } inline uint8_t& as_byte(size_t i) { return *(reinterpret_cast<uint8_t*>(base_ptr)+i); } inline uint8_t* as_byte() { return reinterpret_cast<uint8_t*>(base_ptr); } inline uint64_t& as_uqword(size_t i) { return *(reinterpret_cast<uint64_t*>(base_ptr)+i); } inline const uint64_t& as_uqword(size_t i) const { return *(reinterpret_cast<uint64_t*>(base_ptr)+i); } inline uint64_t* as_uqword() { return reinterpret_cast<uint64_t*>(base_ptr); } inline const uint64_t* as_uqword() const { return reinterpret_cast<uint64_t*>(base_ptr); } inline int64_t& as_qword(size_t i) { return *(reinterpret_cast<int64_t*>(base_ptr)+i); } inline int32_t& as_dword(size_t i) { return *(reinterpret_cast<int32_t*>(base_ptr)+i); } inline uint32_t& as_udword(size_t i) { return *(reinterpret_cast<uint32_t*>(base_ptr)+i); } inline const uint32_t& as_udword(size_t i) const { return *(reinterpret_cast<uint32_t*>(base_ptr)+i); } #ifdef HAS_INTEL_HW inline __m128i* as_xmm() { return reinterpret_cast<__m128i*>(base_ptr); } #endif private: void* base_ptr; }; template<size_t MEMORY, size_t ITER, size_t VERSION> class cn_slow_hash; using cn_pow_hash_v1 = cn_slow_hash<2*1024*1024, 0x80000, 0>; using cn_pow_hash_v2 = cn_slow_hash<4*1024*1024, 0x40000, 1>; using cn_pow_hash_v3 = cn_slow_hash<2*1024*1024, 0x20000, 2>; template<size_t MEMORY, size_t ITER, size_t VERSION> class cn_slow_hash { public: cn_slow_hash() : borrowed_pad(false) { lpad.set(boost::alignment::aligned_alloc(4096, MEMORY)); spad.set(boost::alignment::aligned_alloc(4096, 4096)); } cn_slow_hash (cn_slow_hash&& other) noexcept : lpad(other.lpad.as_byte()), spad(other.spad.as_byte()), borrowed_pad(other.borrowed_pad) { other.lpad.set(nullptr); other.spad.set(nullptr); } // Factory function enabling to temporaliy turn v2 object into v1 // It is caller's responsibility to ensure that v2 object is not hashing at the same time!! static cn_pow_hash_v1 make_borrowed_v1(cn_pow_hash_v3& t) { return cn_pow_hash_v1(t.lpad.as_void(), t.spad.as_void()); } static cn_pow_hash_v2 make_borrowed_v2(cn_pow_hash_v3& t) { return cn_pow_hash_v2(t.lpad.as_void(), t.spad.as_void()); } cn_slow_hash& operator= (cn_slow_hash&& other) noexcept { if(this == &other) return *this; free_mem(); lpad.set(other.lpad.as_void()); spad.set(other.spad.as_void()); borrowed_pad = other.borrowed_pad; return *this; } // Copying is going to be really inefficient cn_slow_hash(const cn_slow_hash& other) = delete; cn_slow_hash& operator= (const cn_slow_hash& other) = delete; ~cn_slow_hash() { free_mem(); } void hash(const void* in, size_t len, void* out) { if(hw_check_aes() && !check_override()) hardware_hash(in, len, out); else software_hash(in, len, out); } void hashc29(const void* in, size_t len, uint32_t nonce, uint32_t *edges, void* out) { cu->hash(in,len,nonce,edges,out); } void software_hash(const void* in, size_t len, void* out); #if !defined(HAS_INTEL_HW) && !defined(HAS_ARM_HW) inline void hardware_hash(const void* in, size_t len, void* out) { assert(false); } #else void hardware_hash(const void* in, size_t len, void* out); #endif private: static constexpr size_t MASK = ((MEMORY-1) >> 4) << 4; friend cn_pow_hash_v1; friend cn_pow_hash_v2; friend cn_pow_hash_v3; Cuckaroo29S* cu = new Cuckaroo29S(); // Constructor enabling v1 hash to borrow v2's buffer cn_slow_hash(void* lptr, void* sptr) { lpad.set(lptr); spad.set(sptr); borrowed_pad = true; } inline bool check_override() { const char *env = getenv("SUMO_USE_SOFTWARE_AES"); if (!env) { return false; } else if (!strcmp(env, "0") || !strcmp(env, "no")) { return false; } else { return true; } } inline void free_mem() { if(!borrowed_pad) { if(lpad.as_void() != nullptr) boost::alignment::aligned_free(lpad.as_void()); if(lpad.as_void() != nullptr) boost::alignment::aligned_free(spad.as_void()); } lpad.set(nullptr); spad.set(nullptr); } inline cn_sptr scratchpad_ptr(uint32_t idx) { return lpad.as_byte() + (idx & MASK); } #if !defined(HAS_INTEL_HW) && !defined(HAS_ARM_HW) inline void explode_scratchpad_hard() { assert(false); } inline void implode_scratchpad_hard() { assert(false); } #else void explode_scratchpad_hard(); void implode_scratchpad_hard(); #endif void explode_scratchpad_soft(); void implode_scratchpad_soft(); cn_sptr lpad; cn_sptr spad; bool borrowed_pad; }; extern template class cn_slow_hash<2*1024*1024, 0x80000, 0>; extern template class cn_slow_hash<4*1024*1024, 0x40000, 1>; extern template class cn_slow_hash<2*1024*1024, 0x20000, 2>; void c29_find_edges(const void*, size_t, uint32_t, uint32_t*);
3C_Header: sHeaderInit ; Z80 offset is $C20B sHeaderPatch 3C_Patches sHeaderTick $01 sHeaderCh $01 sHeaderSFX $80, $04, 3C_FM4, $0C, $05 3C_FM4: sPatFM $00 dc.b nRst, $01 ssModZ80 $03, $01, $09, $FF dc.b nCs6, $25 ssModZ80 $00, $01, $00, $00 3C_Loop1: dc.b sHold saVolFM $01 dc.b nCs6, $02 sLoop $00, $2A, 3C_Loop1 sStop 3C_Patches: ; Patch $00 ; $3C ; $00, $44, $02, $02, $1F, $1F, $1F, $15 ; $00, $1F, $00, $00, $00, $00, $00, $00 ; $0F, $0F, $0F, $0F, $0D, $80, $28, $80 spAlgorithm $04 spFeedback $07 spDetune $00, $00, $04, $00 spMultiple $00, $02, $04, $02 spRateScale $00, $00, $00, $00 spAttackRt $1F, $1F, $1F, $15 spAmpMod $00, $00, $00, $00 spSustainRt $00, $00, $1F, $00 spSustainLv $00, $00, $00, $00 spDecayRt $00, $00, $00, $00 spReleaseRt $0F, $0F, $0F, $0F spTotalLv $0D, $28, $00, $00
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2020 The SolD Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/signverifymessagedialog.h> #include <qt/forms/ui_signverifymessagedialog.h> #include <qt/addressbookpage.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <base58.h> #include <init.h> #include <validation.h> // For strMessageMagic #include <wallet/wallet.h> #include <string> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget* parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); pageButtons.addButton(ui->btnSignMessage, pageButtons.buttons().size()); pageButtons.addButton(ui->btnVerifyMessage, pageButtons.buttons().size()); connect(&pageButtons, SIGNAL(buttonClicked(int)), this, SLOT(showPage(int))); #if QT_VERSION >= 0x040700 ui->messageIn_SM->setPlaceholderText(tr("Enter a message to be signed")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->messageIn_VM->setPlaceholderText(tr("Enter a message to be verified")); ui->signatureIn_VM->setPlaceholderText(tr("Enter a signature for the message to be verified")); #endif GUIUtil::setIcon(ui->addressBookButton_SM, "address-book"); GUIUtil::setIcon(ui->pasteButton_SM, "editpaste"); GUIUtil::setIcon(ui->copySignatureButton_SM, "editcopy"); GUIUtil::setIcon(ui->addressBookButton_VM, "address-book"); GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); GUIUtil::setFont({ui->signatureOut_SM, ui->signatureIn_VM}, GUIUtil::FontWeight::Normal, 11, true); GUIUtil::setFont({ui->signatureLabel_SM}, GUIUtil::FontWeight::Bold, 16); GUIUtil::setFont({ui->statusLabel_SM, ui->statusLabel_VM}, GUIUtil::FontWeight::Bold); GUIUtil::updateFonts(); GUIUtil::disableMacFocusRect(this); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *_model) { this->model = _model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { showPage(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { showPage(1); if (fShow) this->show(); } void SignVerifyMessageDialog::showPage(int index) { std::vector<QWidget*> vecNormal; QAbstractButton* btnActive = pageButtons.button(index); for (QAbstractButton* button : pageButtons.buttons()) { if (button != btnActive) { vecNormal.push_back(button); } } GUIUtil::setFont({btnActive}, GUIUtil::FontWeight::Bold, 16); GUIUtil::setFont(vecNormal, GUIUtil::FontWeight::Normal, 16); GUIUtil::updateFonts(); ui->stackedWidgetSig->setCurrentIndex(index); btnActive->setChecked(true); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { if (!model) return; /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CTxDestination destination = DecodeDestination(ui->addressIn_SM->text().toStdString()); if (!IsValidDestination(destination)) { ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } const CKeyID* keyID = boost::get<CKeyID>(&destination); if (!keyID) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!model->getPrivKey(*keyID, key)) { ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) { ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_SUCCESS)); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(vchSig.data(), vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { GUIUtil::setClipboard(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CTxDestination destination = DecodeDestination(ui->addressIn_VM->text().toStdString()); if (!IsValidDestination(destination)) { ui->statusLabel_VM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } if (!boost::get<CKeyID>(&destination)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CTxDestination(pubkey.GetID()) == destination)) { ui->statusLabel_VM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR)); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_SUCCESS)); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->stackedWidgetSig->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->stackedWidgetSig->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x1a110, %rsi clflush (%rsi) nop nop nop inc %rbx movl $0x61626364, (%rsi) add $8895, %rcx lea addresses_D_ht+0x2130, %rsi lea addresses_A_ht+0xab90, %rdi nop nop xor $33166, %rbx mov $2, %rcx rep movsl add $20301, %r8 lea addresses_A_ht+0x13330, %rdi nop nop nop nop and $27964, %rcx movb (%rdi), %bl nop nop inc %rdi lea addresses_UC_ht+0x9df0, %rsi lea addresses_normal_ht+0x1bad0, %rdi clflush (%rdi) nop sub %r9, %r9 mov $112, %rcx rep movsl nop nop nop nop nop cmp $8180, %r8 lea addresses_UC_ht+0x8930, %rsi lea addresses_WT_ht+0x123d0, %rdi clflush (%rdi) nop and %r13, %r13 mov $123, %rcx rep movsl nop nop sub $56197, %rbx lea addresses_D_ht+0x12550, %rdi nop add %r13, %r13 mov (%rdi), %esi dec %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %r9 push %rbp push %rdi push %rdx // Store lea addresses_RW+0xf9b8, %r10 nop nop add $55480, %r11 mov $0x5152535455565758, %rdx movq %rdx, %xmm2 movups %xmm2, (%r10) nop nop nop nop nop and $56924, %r11 // Store lea addresses_RW+0x77f8, %r14 dec %r9 movb $0x51, (%r14) nop nop nop nop nop sub $44511, %rdi // Store lea addresses_RW+0x4ca8, %r14 nop nop nop nop nop cmp $28535, %rdx movl $0x51525354, (%r14) nop nop nop cmp $16436, %r9 // Store lea addresses_A+0x8930, %rbp nop nop nop and %rdx, %rdx movw $0x5152, (%rbp) nop nop nop nop sub %r10, %r10 // Store lea addresses_PSE+0xeb70, %r9 nop add $21234, %r14 movl $0x51525354, (%r9) nop dec %r10 // Store lea addresses_UC+0xb930, %r10 nop nop nop nop cmp %r14, %r14 movb $0x51, (%r10) add $52092, %r9 // Store mov $0x60314b0000000208, %r11 nop nop nop nop cmp %rdi, %rdi mov $0x5152535455565758, %r14 movq %r14, %xmm2 movups %xmm2, (%r11) nop nop nop nop add %r10, %r10 // Load lea addresses_WT+0x15e50, %r10 nop nop nop nop nop add $49499, %rdx movb (%r10), %r9b nop and $50864, %r10 // Faulty Load lea addresses_A+0x8930, %rbp nop and %rdi, %rdi movb (%rbp), %dl lea oracles, %r11 and $0xff, %rdx shlq $12, %rdx mov (%r11,%rdx,1), %rdx pop %rdx pop %rdi pop %rbp pop %r9 pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 2, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 4, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 9, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 2, 'size': 16, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': True, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 1, 'same': True, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': True, 'NT': False}} {'51': 25} 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 */
;Author information ; Author name: shaochenren ; Author email: renleo@csu.fullerton.edu ; ;Program information ; Program name: Integer Arithmetic ; Programming languages: One modules in C and one module in X86 ; Date program began: 2020-Sep-14 ; Date program completed: 2020-Sep ; Files in this program: integerdriver.c, arithmetic.asm, r.sh ; Status: Complete. No errors found after extensive testing. ; ;References for this program ; Jorgensen, X86-64 Assembly Language Programming with Ubuntu, Version 1.1.40. ; Robert Plantz, X86 Assembly Programming. [No longer available as a free download] ; ;Purpose ; Show how to perform arithmetic operations on two operands both of type long integer. ; Show how to handle overflow of multiplication. ; ;This file ; File name: arithmetic.asm ; Language: X86-64 with Intel syntax ; Max page width: 132 columns ; Assemble: nasm -f elf64 -l arithmetic.lis -o arithmetic.o arithmetic.asm ; Link: gcc -m64 -no-pie -o current.out driver.o arithmetic.o ;Ref Jorgensen, page 226, "-no-pie" ; Optimal print specification: 132 columns width, 7 points, monospace, 8½x11 paper extern printf ;Reference: Jorgensen book 1.1.40, page48 extern scanf null equ 0 ;Reference: Jorgensen book 1.1.40, page 34. newline equ 10 global arithmetic segment .data welcome db "Welcome to your friendly circle circumference calculator.", newline, null The db "The main program will now call the circle function.", newline, null This db "This circle function is brought to you by shaochen.", newline, null please db "please enter the radius of a circle in a whole number of meters: ", null outputformat1 db "The number %ld was received", 10, 0 quotient db "The circumference of a circle with this radius is %ld and ", 0 remainderformat db "%ld / 7", 10, 0 quotient1 db "The main received this integer: %ld",10,0 farewell db "The integer part of the area will be returned to the main program. Please enjoy your circle. Bye.", 10, 0 nice db "Have a nice day.", 10, 0 stringoutputformat db "%s", 0 signedintegerinputformat db "%ld", null segment .bss segment .text ;Instructions are placed in this segment arithmetic: push rbp ;Backup rbp mov rbp,rsp ;The base pointer now points to top of stack push rdi ;Backup rdi push rsi ;Backup rsi push rdx ;Backup rdx push rcx ;Backup rcx push r8 ;Backup r8 push r9 ;Backup r9 push r10 ;Backup r10 push r11 ;Backup r11 push r12 ;Backup r12 push r13 ;Backup r13 push r14 ;Backup r14 push r15 ;Backup r15 push rbx ;Backup rbx pushf push qword -1 ;Output the welcome message ;This is a group of instructions jointly performing one task. mov qword rdi, stringoutputformat mov qword rsi, welcome mov qword rax, 0 call printf ;output the second sentence mov qword rdi, stringoutputformat mov qword rsi, The mov qword rax, 0 call printf ;output the thrid sentence mov qword rdi, stringoutputformat mov qword rsi, This mov qword rax, 0 call printf ;output the thrid sentence mov qword rdi, stringoutputformat mov qword rsi, please mov qword rax, 0 call printf ;Input the first integer mov qword rdi, signedintegerinputformat push qword -1 ;Place an arbitrary value on the stack; -1 is ok, any quad value will work mov qword rsi, rsp ;Now rsi points to that dummy value on the stack mov qword rax, 0 ;No vector registers call scanf ;Call the external function; the new value is placed into the location that rsi points to pop qword r14 ;First inputted integer is saved in r14 ;Output the value previously entered mov qword rdi, outputformat1 mov rsi, r14 mov qword rdx, r14 ;Both rsi and rdx hold the inputted value as well as r14 mov qword rax, 0 call printf ;product of 44 mov qword rax, r14 ;Copy the first factor (operand) to rax mov qword rdx, 44 ;rdx contains no data we wish to save. imul rdx mov qword r12, rdx ;High order bits are saved in r12 mov qword r13, rax mov qword rax, r13 mov qword rbx, 7 idiv rbx mov r13, rdx mov qword rdi, quotient mov qword rsi, rax ;Copy the quotient to rsi mov qword rdx, rax ;Copy the quotient to rdx mov qword rax, 0 mov r12, rdx call printf ;show the remainderformat mov qword rdi, remainderformat mov qword rsi, r13 ;Copy the remainder to rsi mov qword rdx, r13 ;Copy the remainder to rdx mov qword rax, 0 call printf ;Output the farewell message mov qword rdi, stringoutputformat mov qword rsi, farewell ;The starting address of the string is placed into the second parameter. mov qword rax, 0 call printf mov qword rdi, quotient1 mov qword rsi, r12 ;Copy the quotient to rsi mov qword rdx, r12 ;Copy the quotient to rdx mov qword rax, 0 call printf ;Output the farewell message mov qword rdi, stringoutputformat mov qword rsi, nice ;The starting address of the string is placed into the second parameter. mov qword rax, 0 call printf pop rax ;Remove the extra -1 from the stack popf ;Restore rflags pop rbx ;Restore rbx pop r15 ;Restore r15 pop r14 ;Restore r14 pop r13 ;Restore r13 pop r12 ;Restore r12 pop r11 ;Restore r11 pop r10 ;Restore r10 pop r9 ;Restore r9 pop r8 ;Restore r8 pop rcx ;Restore rcx pop rdx ;Restore rdx pop rsi ;Restore rsi pop rdi ;Restore rdi pop rbp ;Restore rbp mov qword rax, 0 ;Return value 0 indicates successful conclusion. ret ;Pop the integer stack and jump to the address represented by the popped value.
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ /* * testNeoHookean.cpp * DG++ * * Created by Adrian Lew on 10/24/06. * * Copyright (c) 2006 Adrian Lew * * 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 "Material.h" #include <vector> #include <iostream> int main() { NeoHookean NH(1., 2.); if (NH.consistencyTest(NH)) std::cout << "Successful\n"; else std::cout << "Failed\n"; return 1; }
//===--- Decl.cpp - Swift Language Decl ASTs ------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the Decl class and subclasses. // //===----------------------------------------------------------------------===// #include "swift/AST/Decl.h" #include "swift/AST/AccessRequests.h" #include "swift/AST/AccessScope.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/DiagnosticsSema.h" #include "swift/AST/ExistentialLayout.h" #include "swift/AST/Expr.h" #include "swift/AST/ForeignErrorConvention.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/GenericSignatureBuilder.h" #include "swift/AST/Initializer.h" #include "swift/AST/LazyResolver.h" #include "swift/AST/ASTMangler.h" #include "swift/AST/Module.h" #include "swift/AST/NameLookup.h" #include "swift/AST/NameLookupRequests.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Pattern.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/ResilienceExpansion.h" #include "swift/AST/Stmt.h" #include "swift/AST/TypeCheckRequests.h" #include "swift/AST/TypeLoc.h" #include "swift/AST/SwiftNameTranslation.h" #include "clang/Lex/MacroInfo.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include "swift/Basic/Range.h" #include "swift/Basic/StringExtras.h" #include "swift/Basic/Statistic.h" #include "clang/Basic/CharInfo.h" #include "clang/AST/Attr.h" #include "clang/AST/DeclObjC.h" #include <algorithm> using namespace swift; #define DEBUG_TYPE "Serialization" STATISTIC(NumLazyGenericEnvironments, "# of lazily-deserialized generic environments known"); STATISTIC(NumLazyGenericEnvironmentsLoaded, "# of lazily-deserialized generic environments loaded"); const clang::MacroInfo *ClangNode::getAsMacro() const { if (auto MM = getAsModuleMacro()) return MM->getMacroInfo(); return getAsMacroInfo(); } clang::SourceLocation ClangNode::getLocation() const { if (auto D = getAsDecl()) return D->getLocation(); if (auto M = getAsMacro()) return M->getDefinitionLoc(); return clang::SourceLocation(); } clang::SourceRange ClangNode::getSourceRange() const { if (auto D = getAsDecl()) return D->getSourceRange(); if (auto M = getAsMacro()) return clang::SourceRange(M->getDefinitionLoc(), M->getDefinitionEndLoc()); return clang::SourceLocation(); } const clang::Module *ClangNode::getClangModule() const { if (auto *M = getAsModule()) return M; if (auto *ID = dyn_cast_or_null<clang::ImportDecl>(getAsDecl())) return ID->getImportedModule(); return nullptr; } // Only allow allocation of Decls using the allocator in ASTContext. void *Decl::operator new(size_t Bytes, const ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } // Only allow allocation of Modules using the allocator in ASTContext. void *ModuleDecl::operator new(size_t Bytes, const ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } StringRef Decl::getKindName(DeclKind K) { switch (K) { #define DECL(Id, Parent) case DeclKind::Id: return #Id; #include "swift/AST/DeclNodes.def" } llvm_unreachable("bad DeclKind"); } DescriptiveDeclKind Decl::getDescriptiveKind() const { #define TRIVIAL_KIND(Kind) \ case DeclKind::Kind: \ return DescriptiveDeclKind::Kind switch (getKind()) { TRIVIAL_KIND(Import); TRIVIAL_KIND(Extension); TRIVIAL_KIND(EnumCase); TRIVIAL_KIND(TopLevelCode); TRIVIAL_KIND(IfConfig); TRIVIAL_KIND(PoundDiagnostic); TRIVIAL_KIND(PatternBinding); TRIVIAL_KIND(PrecedenceGroup); TRIVIAL_KIND(InfixOperator); TRIVIAL_KIND(PrefixOperator); TRIVIAL_KIND(PostfixOperator); TRIVIAL_KIND(TypeAlias); TRIVIAL_KIND(GenericTypeParam); TRIVIAL_KIND(AssociatedType); TRIVIAL_KIND(Protocol); TRIVIAL_KIND(Subscript); TRIVIAL_KIND(Constructor); TRIVIAL_KIND(Destructor); TRIVIAL_KIND(EnumElement); TRIVIAL_KIND(Param); TRIVIAL_KIND(Module); TRIVIAL_KIND(MissingMember); case DeclKind::Enum: return cast<EnumDecl>(this)->getGenericParams() ? DescriptiveDeclKind::GenericEnum : DescriptiveDeclKind::Enum; case DeclKind::Struct: return cast<StructDecl>(this)->getGenericParams() ? DescriptiveDeclKind::GenericStruct : DescriptiveDeclKind::Struct; case DeclKind::Class: return cast<ClassDecl>(this)->getGenericParams() ? DescriptiveDeclKind::GenericClass : DescriptiveDeclKind::Class; case DeclKind::Var: { auto var = cast<VarDecl>(this); switch (var->getCorrectStaticSpelling()) { case StaticSpellingKind::None: if (var->getDeclContext()->isTypeContext()) return DescriptiveDeclKind::Property; return var->isLet() ? DescriptiveDeclKind::Let : DescriptiveDeclKind::Var; case StaticSpellingKind::KeywordStatic: return DescriptiveDeclKind::StaticProperty; case StaticSpellingKind::KeywordClass: return DescriptiveDeclKind::ClassProperty; } } case DeclKind::Accessor: { auto accessor = cast<AccessorDecl>(this); switch (accessor->getAccessorKind()) { case AccessorKind::Get: return DescriptiveDeclKind::Getter; case AccessorKind::Set: return DescriptiveDeclKind::Setter; case AccessorKind::WillSet: return DescriptiveDeclKind::WillSet; case AccessorKind::DidSet: return DescriptiveDeclKind::DidSet; case AccessorKind::Address: return DescriptiveDeclKind::Addressor; case AccessorKind::MutableAddress: return DescriptiveDeclKind::MutableAddressor; case AccessorKind::MaterializeForSet: return DescriptiveDeclKind::MaterializeForSet; case AccessorKind::Read: return DescriptiveDeclKind::ReadAccessor; case AccessorKind::Modify: return DescriptiveDeclKind::ModifyAccessor; } llvm_unreachable("bad accessor kind"); } case DeclKind::Func: { auto func = cast<FuncDecl>(this); if (func->isOperator()) return DescriptiveDeclKind::OperatorFunction; if (func->getDeclContext()->isLocalContext()) return DescriptiveDeclKind::LocalFunction; if (func->getDeclContext()->isModuleScopeContext()) return DescriptiveDeclKind::GlobalFunction; // We have a method. switch (func->getCorrectStaticSpelling()) { case StaticSpellingKind::None: return DescriptiveDeclKind::Method; case StaticSpellingKind::KeywordStatic: return DescriptiveDeclKind::StaticMethod; case StaticSpellingKind::KeywordClass: return DescriptiveDeclKind::ClassMethod; } } } #undef TRIVIAL_KIND llvm_unreachable("bad DescriptiveDeclKind"); } StringRef Decl::getDescriptiveKindName(DescriptiveDeclKind K) { #define ENTRY(Kind, String) case DescriptiveDeclKind::Kind: return String switch (K) { ENTRY(Import, "import"); ENTRY(Extension, "extension"); ENTRY(EnumCase, "case"); ENTRY(TopLevelCode, "top-level code"); ENTRY(IfConfig, "conditional block"); ENTRY(PoundDiagnostic, "diagnostic"); ENTRY(PatternBinding, "pattern binding"); ENTRY(Var, "var"); ENTRY(Param, "parameter"); ENTRY(Let, "let"); ENTRY(Property, "property"); ENTRY(StaticProperty, "static property"); ENTRY(ClassProperty, "class property"); ENTRY(PrecedenceGroup, "precedence group"); ENTRY(InfixOperator, "infix operator"); ENTRY(PrefixOperator, "prefix operator"); ENTRY(PostfixOperator, "postfix operator"); ENTRY(TypeAlias, "type alias"); ENTRY(GenericTypeParam, "generic parameter"); ENTRY(AssociatedType, "associated type"); ENTRY(Type, "type"); ENTRY(Enum, "enum"); ENTRY(Struct, "struct"); ENTRY(Class, "class"); ENTRY(Protocol, "protocol"); ENTRY(GenericEnum, "generic enum"); ENTRY(GenericStruct, "generic struct"); ENTRY(GenericClass, "generic class"); ENTRY(GenericType, "generic type"); ENTRY(Subscript, "subscript"); ENTRY(Constructor, "initializer"); ENTRY(Destructor, "deinitializer"); ENTRY(LocalFunction, "local function"); ENTRY(GlobalFunction, "global function"); ENTRY(OperatorFunction, "operator function"); ENTRY(Method, "instance method"); ENTRY(StaticMethod, "static method"); ENTRY(ClassMethod, "class method"); ENTRY(Getter, "getter"); ENTRY(Setter, "setter"); ENTRY(WillSet, "willSet observer"); ENTRY(DidSet, "didSet observer"); ENTRY(MaterializeForSet, "materializeForSet accessor"); ENTRY(Addressor, "address accessor"); ENTRY(MutableAddressor, "mutableAddress accessor"); ENTRY(ReadAccessor, "_read accessor"); ENTRY(ModifyAccessor, "_modify accessor"); ENTRY(EnumElement, "enum case"); ENTRY(Module, "module"); ENTRY(MissingMember, "missing member placeholder"); ENTRY(Requirement, "requirement"); } #undef ENTRY llvm_unreachable("bad DescriptiveDeclKind"); } llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS, StaticSpellingKind SSK) { switch (SSK) { case StaticSpellingKind::None: return OS << "<none>"; case StaticSpellingKind::KeywordStatic: return OS << "'static'"; case StaticSpellingKind::KeywordClass: return OS << "'class'"; } llvm_unreachable("bad StaticSpellingKind"); } llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS, ReferenceOwnership RO) { if (RO == ReferenceOwnership::Strong) return OS << "'strong'"; return OS << "'" << keywordOf(RO) << "'"; } DeclContext *Decl::getInnermostDeclContext() const { if (auto func = dyn_cast<AbstractFunctionDecl>(this)) return const_cast<AbstractFunctionDecl*>(func); if (auto subscript = dyn_cast<SubscriptDecl>(this)) return const_cast<SubscriptDecl*>(subscript); if (auto type = dyn_cast<GenericTypeDecl>(this)) return const_cast<GenericTypeDecl*>(type); if (auto ext = dyn_cast<ExtensionDecl>(this)) return const_cast<ExtensionDecl*>(ext); if (auto topLevel = dyn_cast<TopLevelCodeDecl>(this)) return const_cast<TopLevelCodeDecl*>(topLevel); return getDeclContext(); } void Decl::setDeclContext(DeclContext *DC) { Context = DC; } bool Decl::isUserAccessible() const { if (auto VD = dyn_cast<ValueDecl>(this)) { return VD->isUserAccessible(); } return true; } bool Decl::canHaveComment() const { return !this->hasClangNode() && (isa<ValueDecl>(this) || isa<ExtensionDecl>(this)) && !isa<ParamDecl>(this) && (!isa<AbstractTypeParamDecl>(this) || isa<AssociatedTypeDecl>(this)); } ModuleDecl *Decl::getModuleContext() const { return getDeclContext()->getParentModule(); } /// Retrieve the diagnostic engine for diagnostics emission. DiagnosticEngine &Decl::getDiags() const { return getASTContext().Diags; } // Helper functions to verify statically whether source-location // functions have been overridden. typedef const char (&TwoChars)[2]; template<typename Class> inline char checkSourceLocType(SourceLoc (Class::*)() const); inline TwoChars checkSourceLocType(SourceLoc (Decl::*)() const); template<typename Class> inline char checkSourceRangeType(SourceRange (Class::*)() const); inline TwoChars checkSourceRangeType(SourceRange (Decl::*)() const); SourceRange Decl::getSourceRange() const { switch (getKind()) { #define DECL(ID, PARENT) \ static_assert(sizeof(checkSourceRangeType(&ID##Decl::getSourceRange)) == 1, \ #ID "Decl is missing getSourceRange()"); \ case DeclKind::ID: return cast<ID##Decl>(this)->getSourceRange(); #include "swift/AST/DeclNodes.def" } llvm_unreachable("Unknown decl kind"); } SourceRange Decl::getSourceRangeIncludingAttrs() const { auto Range = getSourceRange(); // Attributes on AccessorDecl may syntactically belong to PatternBindingDecl. // e.g. 'override'. if (auto *AD = dyn_cast<AccessorDecl>(this)) { // If this is implicit getter, accessor range should not include attributes. if (!AD->getAccessorKeywordLoc().isValid()) return Range; // Otherwise, include attributes directly attached to the accessor. SourceLoc VarLoc = AD->getStorage()->getStartLoc(); for (auto Attr : getAttrs()) { if (!Attr->getRange().isValid()) continue; SourceLoc AttrStartLoc = Attr->getRangeWithAt().Start; if (getASTContext().SourceMgr.isBeforeInBuffer(VarLoc, AttrStartLoc)) Range.widen(AttrStartLoc); } return Range; } // Attributes on VarDecl syntactically belong to PatternBindingDecl. if (isa<VarDecl>(this)) return Range; // Attributes on PatternBindingDecls are attached to VarDecls in AST. if (auto *PBD = dyn_cast<PatternBindingDecl>(this)) { for (auto Entry : PBD->getPatternList()) Entry.getPattern()->forEachVariable([&](VarDecl *VD) { for (auto Attr : VD->getAttrs()) if (Attr->getRange().isValid()) Range.widen(Attr->getRangeWithAt()); }); } for (auto Attr : getAttrs()) { if (Attr->getRange().isValid()) Range.widen(Attr->getRangeWithAt()); } return Range; } SourceLoc Decl::getLoc() const { switch (getKind()) { #define DECL(ID, X) \ static_assert(sizeof(checkSourceLocType(&ID##Decl::getLoc)) == 1, \ #ID "Decl is missing getLoc()"); \ case DeclKind::ID: return cast<ID##Decl>(this)->getLoc(); #include "swift/AST/DeclNodes.def" } llvm_unreachable("Unknown decl kind"); } SourceLoc BehaviorRecord::getLoc() const { return ProtocolName->getLoc(); } bool AbstractStorageDecl::isTransparent() const { return getAttrs().hasAttribute<TransparentAttr>(); } bool AbstractFunctionDecl::isTransparent() const { // Check if the declaration had the attribute. if (getAttrs().hasAttribute<TransparentAttr>()) return true; // If this is an accessor, check if the transparent attribute was set // on the storage decl. if (const auto *AD = dyn_cast<AccessorDecl>(this)) { return AD->getStorage()->isTransparent(); } return false; } bool Decl::isPrivateStdlibDecl(bool treatNonBuiltinProtocolsAsPublic) const { const Decl *D = this; if (auto ExtD = dyn_cast<ExtensionDecl>(D)) { Type extTy = ExtD->getExtendedType(); return extTy.isPrivateStdlibType(treatNonBuiltinProtocolsAsPublic); } DeclContext *DC = D->getDeclContext()->getModuleScopeContext(); if (DC->getParentModule()->isBuiltinModule() || DC->getParentModule()->isSwiftShimsModule()) return true; if (!DC->getParentModule()->isSystemModule()) return false; auto FU = dyn_cast<FileUnit>(DC); if (!FU) return false; // Check for Swift module and overlays. if (!DC->getParentModule()->isStdlibModule() && FU->getKind() != FileUnitKind::SerializedAST) return false; auto hasInternalParameter = [](const ParameterList *params) -> bool { for (auto param : *params) { if (param->hasName() && param->getNameStr().startswith("_")) return true; auto argName = param->getArgumentName(); if (!argName.empty() && argName.str().startswith("_")) return true; } return false; }; if (auto AFD = dyn_cast<AbstractFunctionDecl>(D)) { // If it's a function with a parameter with leading underscore, it's a // private function. if (hasInternalParameter(AFD->getParameters())) return true; } if (auto SubscriptD = dyn_cast<SubscriptDecl>(D)) { if (hasInternalParameter(SubscriptD->getIndices())) return true; } if (auto PD = dyn_cast<ProtocolDecl>(D)) { if (PD->getAttrs().hasAttribute<ShowInInterfaceAttr>()) return false; StringRef NameStr = PD->getNameStr(); if (NameStr.startswith("_Builtin")) return true; if (NameStr.startswith("_ExpressibleBy")) return true; if (treatNonBuiltinProtocolsAsPublic) return false; } if (auto ImportD = dyn_cast<ImportDecl>(D)) { if (ImportD->getModule()->isSwiftShimsModule()) return true; } auto VD = dyn_cast<ValueDecl>(D); if (!VD || !VD->hasName()) return false; // If the name has leading underscore then it's a private symbol. if (!VD->getBaseName().isSpecial() && VD->getBaseName().getIdentifier().str().startswith("_")) return true; return false; } bool Decl::isWeakImported(ModuleDecl *fromModule) const { // For a Clang declaration, trust Clang. if (auto clangDecl = getClangDecl()) { return clangDecl->isWeakImported(); } auto *containingModule = getModuleContext(); if (containingModule == fromModule) return false; if (getAttrs().hasAttribute<WeakLinkedAttr>()) return true; // FIXME: Also check availability when containingModule is resilient. return false; } GenericParamList::GenericParamList(SourceLoc LAngleLoc, ArrayRef<GenericTypeParamDecl *> Params, SourceLoc WhereLoc, MutableArrayRef<RequirementRepr> Requirements, SourceLoc RAngleLoc) : Brackets(LAngleLoc, RAngleLoc), NumParams(Params.size()), WhereLoc(WhereLoc), Requirements(Requirements), OuterParameters(nullptr), FirstTrailingWhereArg(Requirements.size()) { std::uninitialized_copy(Params.begin(), Params.end(), getTrailingObjects<GenericTypeParamDecl *>()); } GenericParamList * GenericParamList::create(ASTContext &Context, SourceLoc LAngleLoc, ArrayRef<GenericTypeParamDecl *> Params, SourceLoc RAngleLoc) { unsigned Size = totalSizeToAlloc<GenericTypeParamDecl *>(Params.size()); void *Mem = Context.Allocate(Size, alignof(GenericParamList)); return new (Mem) GenericParamList(LAngleLoc, Params, SourceLoc(), MutableArrayRef<RequirementRepr>(), RAngleLoc); } GenericParamList * GenericParamList::create(const ASTContext &Context, SourceLoc LAngleLoc, ArrayRef<GenericTypeParamDecl *> Params, SourceLoc WhereLoc, ArrayRef<RequirementRepr> Requirements, SourceLoc RAngleLoc) { unsigned Size = totalSizeToAlloc<GenericTypeParamDecl *>(Params.size()); void *Mem = Context.Allocate(Size, alignof(GenericParamList)); return new (Mem) GenericParamList(LAngleLoc, Params, WhereLoc, Context.AllocateCopy(Requirements), RAngleLoc); } GenericParamList * GenericParamList::clone(DeclContext *dc) const { auto &ctx = dc->getASTContext(); SmallVector<GenericTypeParamDecl *, 2> params; for (auto param : getParams()) { auto *newParam = new (ctx) GenericTypeParamDecl( dc, param->getName(), param->getNameLoc(), GenericTypeParamDecl::InvalidDepth, param->getIndex()); params.push_back(newParam); SmallVector<TypeLoc, 2> inherited; for (auto loc : param->getInherited()) inherited.push_back(loc.clone(ctx)); newParam->setInherited(ctx.AllocateCopy(inherited)); } SmallVector<RequirementRepr, 2> requirements; for (auto reqt : getRequirements()) { switch (reqt.getKind()) { case RequirementReprKind::TypeConstraint: { auto first = reqt.getSubjectLoc(); auto second = reqt.getConstraintLoc(); reqt = RequirementRepr::getTypeConstraint( first.clone(ctx), reqt.getColonLoc(), second.clone(ctx)); break; } case RequirementReprKind::SameType: { auto first = reqt.getFirstTypeLoc(); auto second = reqt.getSecondTypeLoc(); reqt = RequirementRepr::getSameType( first.clone(ctx), reqt.getEqualLoc(), second.clone(ctx)); break; } case RequirementReprKind::LayoutConstraint: { auto first = reqt.getSubjectLoc(); auto layout = reqt.getLayoutConstraintLoc(); reqt = RequirementRepr::getLayoutConstraint( first.clone(ctx), reqt.getColonLoc(), layout); break; } } requirements.push_back(reqt); } return GenericParamList::create(ctx, getLAngleLoc(), params, getWhereLoc(), requirements, getRAngleLoc()); } void GenericParamList::addTrailingWhereClause( ASTContext &ctx, SourceLoc trailingWhereLoc, ArrayRef<RequirementRepr> trailingRequirements) { assert(TrailingWhereLoc.isInvalid() && "Already have a trailing where clause?"); TrailingWhereLoc = trailingWhereLoc; FirstTrailingWhereArg = Requirements.size(); // Create a unified set of requirements. auto newRequirements = ctx.AllocateUninitialized<RequirementRepr>( Requirements.size() + trailingRequirements.size()); std::memcpy(newRequirements.data(), Requirements.data(), Requirements.size() * sizeof(RequirementRepr)); std::memcpy(newRequirements.data() + Requirements.size(), trailingRequirements.data(), trailingRequirements.size() * sizeof(RequirementRepr)); Requirements = newRequirements; } TrailingWhereClause::TrailingWhereClause( SourceLoc whereLoc, ArrayRef<RequirementRepr> requirements) : WhereLoc(whereLoc), NumRequirements(requirements.size()) { std::uninitialized_copy(requirements.begin(), requirements.end(), getTrailingObjects<RequirementRepr>()); } TrailingWhereClause *TrailingWhereClause::create( ASTContext &ctx, SourceLoc whereLoc, ArrayRef<RequirementRepr> requirements) { unsigned size = totalSizeToAlloc<RequirementRepr>(requirements.size()); void *mem = ctx.Allocate(size, alignof(TrailingWhereClause)); return new (mem) TrailingWhereClause(whereLoc, requirements); } TypeArrayView<GenericTypeParamType> GenericContext::getInnermostGenericParamTypes() const { if (auto sig = getGenericSignature()) return sig->getInnermostGenericParams(); else return { }; } /// Retrieve the generic requirements. ArrayRef<Requirement> GenericContext::getGenericRequirements() const { if (auto sig = getGenericSignature()) return sig->getRequirements(); else return { }; } void GenericContext::setGenericParams(GenericParamList *params) { GenericParams = params; if (GenericParams) { for (auto param : *GenericParams) param->setDeclContext(this); } } GenericSignature *GenericContext::getGenericSignature() const { if (auto genericEnv = GenericSigOrEnv.dyn_cast<GenericEnvironment *>()) return genericEnv->getGenericSignature(); if (auto genericSig = GenericSigOrEnv.dyn_cast<GenericSignature *>()) return genericSig; // The signature of a Protocol is trivial (Self: TheProtocol) so let's compute // it. if (auto PD = dyn_cast<ProtocolDecl>(this)) { auto self = PD->getSelfInterfaceType()->castTo<GenericTypeParamType>(); auto req = Requirement(RequirementKind::Conformance, self, PD->getDeclaredType()); return GenericSignature::get({self}, {req}); } return nullptr; } GenericEnvironment *GenericContext::getGenericEnvironment() const { // Fast case: we already have a generic environment. if (auto genericEnv = GenericSigOrEnv.dyn_cast<GenericEnvironment *>()) return genericEnv; // If we only have a generic signature, build the generic environment. if (GenericSigOrEnv.dyn_cast<GenericSignature *>()) return getLazyGenericEnvironmentSlow(); return nullptr; } bool GenericContext::hasLazyGenericEnvironment() const { return GenericSigOrEnv.dyn_cast<GenericSignature *>() != nullptr; } void GenericContext::setGenericEnvironment(GenericEnvironment *genericEnv) { assert((GenericSigOrEnv.isNull() || getGenericSignature()->getCanonicalSignature() == genericEnv->getGenericSignature()->getCanonicalSignature()) && "set a generic environment with a different generic signature"); this->GenericSigOrEnv = genericEnv; if (genericEnv) genericEnv->setOwningDeclContext(this); } GenericEnvironment * GenericContext::getLazyGenericEnvironmentSlow() const { assert(GenericSigOrEnv.is<GenericSignature *>() && "not a lazily deserialized generic environment"); auto contextData = getASTContext().getOrCreateLazyGenericContextData( this, nullptr); auto *genericEnv = contextData->loader->loadGenericEnvironment( this, contextData->genericEnvData); const_cast<GenericContext *>(this)->setGenericEnvironment(genericEnv); ++NumLazyGenericEnvironmentsLoaded; // FIXME: (transitional) increment the redundant "always-on" counter. if (getASTContext().Stats) getASTContext().Stats->getFrontendCounters().NumLazyGenericEnvironmentsLoaded++; return genericEnv; } void GenericContext::setLazyGenericEnvironment(LazyMemberLoader *lazyLoader, GenericSignature *genericSig, uint64_t genericEnvData) { assert(GenericSigOrEnv.isNull() && "already have a generic signature"); GenericSigOrEnv = genericSig; auto contextData = getASTContext().getOrCreateLazyGenericContextData(this, lazyLoader); contextData->genericEnvData = genericEnvData; ++NumLazyGenericEnvironments; // FIXME: (transitional) increment the redundant "always-on" counter. if (getASTContext().Stats) getASTContext().Stats->getFrontendCounters().NumLazyGenericEnvironments++; } SourceRange GenericContext::getGenericTrailingWhereClauseSourceRange() const { if (!isGeneric()) return SourceRange(); return getGenericParams()->getTrailingWhereClauseSourceRange(); } ImportDecl *ImportDecl::create(ASTContext &Ctx, DeclContext *DC, SourceLoc ImportLoc, ImportKind Kind, SourceLoc KindLoc, ArrayRef<AccessPathElement> Path, ClangNode ClangN) { assert(!Path.empty()); assert(Kind == ImportKind::Module || Path.size() > 1); assert(ClangN.isNull() || ClangN.getAsModule() || isa<clang::ImportDecl>(ClangN.getAsDecl())); size_t Size = totalSizeToAlloc<AccessPathElement>(Path.size()); void *ptr = allocateMemoryForDecl<ImportDecl>(Ctx, Size, !ClangN.isNull()); auto D = new (ptr) ImportDecl(DC, ImportLoc, Kind, KindLoc, Path); if (ClangN) D->setClangNode(ClangN); return D; } ImportDecl::ImportDecl(DeclContext *DC, SourceLoc ImportLoc, ImportKind K, SourceLoc KindLoc, ArrayRef<AccessPathElement> Path) : Decl(DeclKind::Import, DC), ImportLoc(ImportLoc), KindLoc(KindLoc) { Bits.ImportDecl.NumPathElements = Path.size(); assert(Bits.ImportDecl.NumPathElements == Path.size() && "Truncation error"); Bits.ImportDecl.ImportKind = static_cast<unsigned>(K); assert(getImportKind() == K && "not enough bits for ImportKind"); std::uninitialized_copy(Path.begin(), Path.end(), getTrailingObjects<AccessPathElement>()); } ImportKind ImportDecl::getBestImportKind(const ValueDecl *VD) { switch (VD->getKind()) { case DeclKind::Import: case DeclKind::Extension: case DeclKind::PatternBinding: case DeclKind::TopLevelCode: case DeclKind::InfixOperator: case DeclKind::PrefixOperator: case DeclKind::PostfixOperator: case DeclKind::EnumCase: case DeclKind::IfConfig: case DeclKind::PoundDiagnostic: case DeclKind::PrecedenceGroup: case DeclKind::MissingMember: llvm_unreachable("not a ValueDecl"); case DeclKind::AssociatedType: case DeclKind::Constructor: case DeclKind::Destructor: case DeclKind::GenericTypeParam: case DeclKind::Subscript: case DeclKind::EnumElement: case DeclKind::Param: llvm_unreachable("not a top-level ValueDecl"); case DeclKind::Protocol: return ImportKind::Protocol; case DeclKind::Class: return ImportKind::Class; case DeclKind::Enum: return ImportKind::Enum; case DeclKind::Struct: return ImportKind::Struct; case DeclKind::TypeAlias: { Type type = cast<TypeAliasDecl>(VD)->getDeclaredInterfaceType(); auto *nominal = type->getAnyNominal(); if (!nominal) return ImportKind::Type; return getBestImportKind(nominal); } case DeclKind::Accessor: case DeclKind::Func: return ImportKind::Func; case DeclKind::Var: return ImportKind::Var; case DeclKind::Module: return ImportKind::Module; } llvm_unreachable("bad DeclKind"); } Optional<ImportKind> ImportDecl::findBestImportKind(ArrayRef<ValueDecl *> Decls) { assert(!Decls.empty()); ImportKind FirstKind = ImportDecl::getBestImportKind(Decls.front()); // FIXME: Only functions can be overloaded. if (Decls.size() == 1) return FirstKind; if (FirstKind != ImportKind::Func) return None; for (auto NextDecl : Decls.slice(1)) { if (ImportDecl::getBestImportKind(NextDecl) != FirstKind) return None; } return FirstKind; } void NominalTypeDecl::setConformanceLoader(LazyMemberLoader *lazyLoader, uint64_t contextData) { assert(!Bits.NominalTypeDecl.HasLazyConformances && "Already have lazy conformances"); Bits.NominalTypeDecl.HasLazyConformances = true; ASTContext &ctx = getASTContext(); auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, lazyLoader); contextInfo->allConformancesData = contextData; } std::pair<LazyMemberLoader *, uint64_t> NominalTypeDecl::takeConformanceLoaderSlow() { assert(Bits.NominalTypeDecl.HasLazyConformances && "not lazy conformances"); Bits.NominalTypeDecl.HasLazyConformances = false; auto contextInfo = getASTContext().getOrCreateLazyIterableContextData(this, nullptr); return { contextInfo->loader, contextInfo->allConformancesData }; } ExtensionDecl::ExtensionDecl(SourceLoc extensionLoc, TypeLoc extendedType, MutableArrayRef<TypeLoc> inherited, DeclContext *parent, TrailingWhereClause *trailingWhereClause) : GenericContext(DeclContextKind::ExtensionDecl, parent), Decl(DeclKind::Extension, parent), IterableDeclContext(IterableDeclContextKind::ExtensionDecl), ExtensionLoc(extensionLoc), ExtendedType(extendedType), Inherited(inherited) { Bits.ExtensionDecl.DefaultAndMaxAccessLevel = 0; Bits.ExtensionDecl.HasLazyConformances = false; setTrailingWhereClause(trailingWhereClause); } ExtensionDecl *ExtensionDecl::create(ASTContext &ctx, SourceLoc extensionLoc, TypeLoc extendedType, MutableArrayRef<TypeLoc> inherited, DeclContext *parent, TrailingWhereClause *trailingWhereClause, ClangNode clangNode) { unsigned size = sizeof(ExtensionDecl); void *declPtr = allocateMemoryForDecl<ExtensionDecl>(ctx, size, !clangNode.isNull()); // Construct the extension. auto result = ::new (declPtr) ExtensionDecl(extensionLoc, extendedType, inherited, parent, trailingWhereClause); if (clangNode) result->setClangNode(clangNode); return result; } void ExtensionDecl::setConformanceLoader(LazyMemberLoader *lazyLoader, uint64_t contextData) { assert(!Bits.ExtensionDecl.HasLazyConformances && "Already have lazy conformances"); Bits.ExtensionDecl.HasLazyConformances = true; ASTContext &ctx = getASTContext(); auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, lazyLoader); contextInfo->allConformancesData = contextData; } std::pair<LazyMemberLoader *, uint64_t> ExtensionDecl::takeConformanceLoaderSlow() { assert(Bits.ExtensionDecl.HasLazyConformances && "no conformance loader?"); Bits.ExtensionDecl.HasLazyConformances = false; auto contextInfo = getASTContext().getOrCreateLazyIterableContextData(this, nullptr); return { contextInfo->loader, contextInfo->allConformancesData }; } NominalTypeDecl *ExtensionDecl::getExtendedNominal() const { ASTContext &ctx = getASTContext(); return ctx.evaluator( ExtendedNominalRequest{const_cast<ExtensionDecl *>(this)});; } Type ExtensionDecl::getInheritedType(unsigned index) const { ASTContext &ctx = getASTContext(); return ctx.evaluator(InheritedTypeRequest{const_cast<ExtensionDecl *>(this), index}); } bool ExtensionDecl::isConstrainedExtension() const { // Non-generic extension. if (!getGenericSignature()) return false; auto nominal = getExtendedNominal(); assert(nominal); // If the generic signature differs from that of the nominal type, it's a // constrained extension. return getGenericSignature()->getCanonicalSignature() != nominal->getGenericSignature()->getCanonicalSignature(); } bool ExtensionDecl::isEquivalentToExtendedContext() const { auto decl = getExtendedNominal(); return getParentModule() == decl->getParentModule() && !isConstrainedExtension() && !getDeclaredInterfaceType()->isExistentialType(); } AccessLevel ExtensionDecl::getDefaultAccessLevel() const { ASTContext &ctx = getASTContext(); return ctx.evaluator( DefaultAndMaxAccessLevelRequest{const_cast<ExtensionDecl *>(this)}).first; } AccessLevel ExtensionDecl::getMaxAccessLevel() const { ASTContext &ctx = getASTContext(); return ctx.evaluator( DefaultAndMaxAccessLevelRequest{const_cast<ExtensionDecl *>(this)}).second; } PatternBindingDecl::PatternBindingDecl(SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, unsigned NumPatternEntries, DeclContext *Parent) : Decl(DeclKind::PatternBinding, Parent), StaticLoc(StaticLoc), VarLoc(VarLoc) { Bits.PatternBindingDecl.IsStatic = StaticLoc.isValid(); Bits.PatternBindingDecl.StaticSpelling = static_cast<unsigned>(StaticSpelling); Bits.PatternBindingDecl.NumPatternEntries = NumPatternEntries; } PatternBindingDecl * PatternBindingDecl::create(ASTContext &Ctx, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, Pattern *Pat, SourceLoc EqualLoc, Expr *E, DeclContext *Parent) { DeclContext *BindingInitContext = nullptr; if (!Parent->isLocalContext()) BindingInitContext = new (Ctx) PatternBindingInitializer(Parent); auto PBE = PatternBindingEntry(Pat, EqualLoc, E, BindingInitContext); auto *Result = create(Ctx, StaticLoc, StaticSpelling, VarLoc, PBE, Parent); if (BindingInitContext) cast<PatternBindingInitializer>(BindingInitContext)->setBinding(Result, 0); return Result; } PatternBindingDecl *PatternBindingDecl::createImplicit( ASTContext &Ctx, StaticSpellingKind StaticSpelling, Pattern *Pat, Expr *E, DeclContext *Parent, SourceLoc VarLoc) { auto *Result = create(Ctx, /*StaticLoc*/ SourceLoc(), StaticSpelling, VarLoc, Pat, /*EqualLoc*/ SourceLoc(), E, Parent); Result->setImplicit(); return Result; } PatternBindingDecl * PatternBindingDecl::create(ASTContext &Ctx, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, ArrayRef<PatternBindingEntry> PatternList, DeclContext *Parent) { size_t Size = totalSizeToAlloc<PatternBindingEntry>(PatternList.size()); void *D = allocateMemoryForDecl<PatternBindingDecl>(Ctx, Size, /*ClangNode*/false); auto PBD = ::new (D) PatternBindingDecl(StaticLoc, StaticSpelling, VarLoc, PatternList.size(), Parent); // Set up the patterns. auto entries = PBD->getMutablePatternList(); unsigned elt = 0U-1; for (auto pe : PatternList) { ++elt; auto &newEntry = entries[elt]; newEntry = pe; // This should take care of initializer with flags DeclContext *initContext = pe.getInitContext(); if (!initContext && !Parent->isLocalContext()) { auto pbi = new (Ctx) PatternBindingInitializer(Parent); pbi->setBinding(PBD, elt); initContext = pbi; } PBD->setPattern(elt, pe.getPattern(), initContext); } return PBD; } PatternBindingDecl *PatternBindingDecl::createDeserialized( ASTContext &Ctx, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, unsigned NumPatternEntries, DeclContext *Parent) { size_t Size = totalSizeToAlloc<PatternBindingEntry>(NumPatternEntries); void *D = allocateMemoryForDecl<PatternBindingDecl>(Ctx, Size, /*ClangNode*/false); auto PBD = ::new (D) PatternBindingDecl(StaticLoc, StaticSpelling, VarLoc, NumPatternEntries, Parent); for (auto &entry : PBD->getMutablePatternList()) { entry = PatternBindingEntry(/*Pattern*/ nullptr, /*EqualLoc*/ SourceLoc(), /*Init*/ nullptr, /*InitContext*/ nullptr); } return PBD; } ParamDecl *PatternBindingInitializer::getImplicitSelfDecl() { if (SelfParam) return SelfParam; if (auto singleVar = getInitializedLazyVar()) { auto DC = singleVar->getDeclContext(); if (DC->isTypeContext()) { bool isInOut = !DC->getDeclaredInterfaceType()->hasReferenceSemantics(); SelfParam = ParamDecl::createSelf(SourceLoc(), DC, singleVar->isStatic(), isInOut); SelfParam->setDeclContext(this); } } return SelfParam; } VarDecl *PatternBindingInitializer::getInitializedLazyVar() const { if (auto var = getBinding()->getSingleVar()) { if (var->getAttrs().hasAttribute<LazyAttr>()) return var; } return nullptr; } static bool patternContainsVarDeclBinding(const Pattern *P, const VarDecl *VD) { bool Result = false; P->forEachVariable([&](VarDecl *FoundVD) { Result |= FoundVD == VD; }); return Result; } unsigned PatternBindingDecl::getPatternEntryIndexForVarDecl(const VarDecl *VD) const { assert(VD && "Cannot find a null VarDecl"); auto List = getPatternList(); if (List.size() == 1) { assert(patternContainsVarDeclBinding(List[0].getPattern(), VD) && "Single entry PatternBindingDecl is set up wrong"); return 0; } unsigned Result = 0; for (auto entry : List) { if (patternContainsVarDeclBinding(entry.getPattern(), VD)) return Result; ++Result; } assert(0 && "PatternBindingDecl doesn't bind the specified VarDecl!"); return ~0U; } SourceRange PatternBindingEntry::getOrigInitRange() const { auto Init = InitAndFlags.getPointer(); return Init ? Init->getSourceRange() : SourceRange(); } void PatternBindingEntry::setInit(Expr *E) { auto F = InitAndFlags.getInt(); if (E) { InitAndFlags.setInt(F - Flags::Removed); InitAndFlags.setPointer(E); } else { InitAndFlags.setInt(F | Flags::Removed); } } VarDecl *PatternBindingEntry::getAnchoringVarDecl() const { SmallVector<VarDecl *, 8> variables; getPattern()->collectVariables(variables); assert(!variables.empty()); return variables[0]; } SourceRange PatternBindingEntry::getSourceRange(bool omitAccessors) const { // Patterns end at the initializer, if present. SourceLoc endLoc = getOrigInitRange().End; // If we're not banned from handling accessors, they follow the initializer. if (!omitAccessors) { getPattern()->forEachVariable([&](VarDecl *var) { auto accessorsEndLoc = var->getBracesRange().End; if (accessorsEndLoc.isValid()) endLoc = accessorsEndLoc; }); } // If we didn't find an end yet, check the pattern. if (endLoc.isInvalid()) endLoc = getPattern()->getEndLoc(); SourceLoc startLoc = getPattern()->getStartLoc(); if (startLoc.isValid() != endLoc.isValid()) return SourceRange(); return SourceRange(startLoc, endLoc); } SourceRange PatternBindingDecl::getSourceRange() const { SourceLoc startLoc = getStartLoc(); SourceLoc endLoc = getPatternList().back().getSourceRange().End; if (startLoc.isValid() != endLoc.isValid()) return SourceRange(); return { startLoc, endLoc }; } static StaticSpellingKind getCorrectStaticSpellingForDecl(const Decl *D) { if (!D->getDeclContext()->getAsClassOrClassExtensionContext()) return StaticSpellingKind::KeywordStatic; return StaticSpellingKind::KeywordClass; } StaticSpellingKind PatternBindingDecl::getCorrectStaticSpelling() const { if (!isStatic()) return StaticSpellingKind::None; if (getStaticSpelling() != StaticSpellingKind::None) return getStaticSpelling(); return getCorrectStaticSpellingForDecl(this); } bool PatternBindingDecl::hasStorage() const { // Walk the pattern, to check to see if any of the VarDecls included in it // have storage. for (auto entry : getPatternList()) if (entry.getPattern()->hasStorage()) return true; return false; } void PatternBindingDecl::setPattern(unsigned i, Pattern *P, DeclContext *InitContext) { auto PatternList = getMutablePatternList(); PatternList[i].setPattern(P); PatternList[i].setInitContext(InitContext); // Make sure that any VarDecl's contained within the pattern know about this // PatternBindingDecl as their parent. if (P) P->forEachVariable([&](VarDecl *VD) { VD->setParentPatternBinding(this); }); } VarDecl *PatternBindingDecl::getSingleVar() const { if (getNumPatternEntries() == 1) return getPatternList()[0].getPattern()->getSingleVar(); return nullptr; } /// Check whether the given type representation will be /// default-initializable. static bool isDefaultInitializable(const TypeRepr *typeRepr) { // Look through most attributes. if (const auto attributed = dyn_cast<AttributedTypeRepr>(typeRepr)) { // Ownership kinds have optionalness requirements. if (optionalityOf(attributed->getAttrs().getOwnership()) == ReferenceOwnershipOptionality::Required) return true; return isDefaultInitializable(attributed->getTypeRepr()); } // Optional types are default-initializable. if (isa<OptionalTypeRepr>(typeRepr) || isa<ImplicitlyUnwrappedOptionalTypeRepr>(typeRepr)) return true; // Tuple types are default-initializable if all of their element // types are. if (const auto tuple = dyn_cast<TupleTypeRepr>(typeRepr)) { // ... but not variadic ones. if (tuple->hasEllipsis()) return false; for (const auto elt : tuple->getElements()) { if (!isDefaultInitializable(elt.Type)) return false; } return true; } // Not default initializable. return false; } // @NSManaged properties never get default initialized, nor do debugger // variables and immutable properties. bool Pattern::isNeverDefaultInitializable() const { bool result = false; forEachVariable([&](const VarDecl *var) { if (var->getAttrs().hasAttribute<NSManagedAttr>()) return; if (var->isDebuggerVar() || var->isLet()) result = true; }); return result; } bool PatternBindingDecl::isDefaultInitializable(unsigned i) const { const auto entry = getPatternList()[i]; // If it has an initializer expression, this is trivially true. if (entry.getInit()) return true; if (entry.getPattern()->isNeverDefaultInitializable()) return false; // If the pattern is typed as optional (or tuples thereof), it is // default initializable. if (const auto typedPattern = dyn_cast<TypedPattern>(entry.getPattern())) { if (const auto typeRepr = typedPattern->getTypeLoc().getTypeRepr()) { if (::isDefaultInitializable(typeRepr)) return true; } else if (typedPattern->isImplicit()) { // Lazy vars have implicit storage assigned to back them. Because the // storage is implicit, the pattern is typed and has a TypeLoc, but not a // TypeRepr. // // All lazy storage is implicitly default initializable, though, because // lazy backing storage is optional. if (const auto *varDecl = typedPattern->getSingleVar()) // Lazy storage is never user accessible. if (!varDecl->isUserAccessible()) if (typedPattern->getTypeLoc().getType()->getOptionalObjectType()) return true; } } // Otherwise, we can't default initialize this binding. return false; } SourceLoc TopLevelCodeDecl::getStartLoc() const { return Body->getStartLoc(); } SourceRange TopLevelCodeDecl::getSourceRange() const { return Body->getSourceRange(); } SourceRange IfConfigDecl::getSourceRange() const { return SourceRange(getLoc(), EndLoc); } static bool isPolymorphic(const AbstractStorageDecl *storage) { if (storage->isDynamic()) return true; // Imported declarations behave like they are dynamic, even if they're // not marked as such explicitly. if (storage->isObjC() && storage->hasClangNode()) return true; if (auto *classDecl = dyn_cast<ClassDecl>(storage->getDeclContext())) { if (storage->isFinal() || classDecl->isFinal()) return false; return true; } if (isa<ProtocolDecl>(storage->getDeclContext())) return true; return false; } /// Determines the access semantics to use in a DeclRefExpr or /// MemberRefExpr use of this value in the specified context. AccessSemantics ValueDecl::getAccessSemanticsFromContext(const DeclContext *UseDC, bool isAccessOnSelf) const { // All accesses have ordinary semantics except those to variables // with storage from within their own accessors. In Swift 5 and later, // the access must also be a member access on 'self'. // The condition most likely to fast-path us is not being in an accessor, // so we check that first. if (auto *accessor = dyn_cast<AccessorDecl>(UseDC)) { if (auto *var = dyn_cast<VarDecl>(this)) { if (accessor->getStorage() == var && var->hasStorage() && (isAccessOnSelf || !var->getDeclContext()->isTypeContext() || !var->getASTContext().isSwiftVersionAtLeast(5))) return AccessSemantics::DirectToStorage; } } // Otherwise, it's a semantically normal access. The client should be // able to figure out the most efficient way to do this access. return AccessSemantics::Ordinary; } static AccessStrategy getDirectReadAccessStrategy(const AbstractStorageDecl *storage) { switch (storage->getReadImpl()) { case ReadImplKind::Stored: return AccessStrategy::getStorage(); case ReadImplKind::Inherited: // TODO: maybe add a specific strategy for this? return AccessStrategy::getAccessor(AccessorKind::Get, /*dispatch*/ false); case ReadImplKind::Get: return AccessStrategy::getAccessor(AccessorKind::Get, /*dispatch*/ false); case ReadImplKind::Address: return AccessStrategy::getAccessor(AccessorKind::Address, /*dispatch*/ false); case ReadImplKind::Read: return AccessStrategy::getAccessor(AccessorKind::Read, /*dispatch*/ false); } llvm_unreachable("bad impl kind"); } static AccessStrategy getDirectWriteAccessStrategy(const AbstractStorageDecl *storage) { switch (storage->getWriteImpl()) { case WriteImplKind::Immutable: assert(isa<VarDecl>(storage) && cast<VarDecl>(storage)->isLet() && "mutation of a immutable variable that isn't a let"); return AccessStrategy::getStorage(); case WriteImplKind::Stored: return AccessStrategy::getStorage(); case WriteImplKind::StoredWithObservers: // TODO: maybe add a specific strategy for this? return AccessStrategy::getAccessor(AccessorKind::Set, /*dispatch*/ false); case WriteImplKind::InheritedWithObservers: // TODO: maybe add a specific strategy for this? return AccessStrategy::getAccessor(AccessorKind::Set, /*dispatch*/ false); case WriteImplKind::Set: return AccessStrategy::getAccessor(AccessorKind::Set, /*dispatch*/ false); case WriteImplKind::MutableAddress: return AccessStrategy::getAccessor(AccessorKind::MutableAddress, /*dispatch*/ false); case WriteImplKind::Modify: return AccessStrategy::getAccessor(AccessorKind::Modify, /*dispatch*/ false); } llvm_unreachable("bad impl kind"); } static AccessStrategy getDirectReadWriteAccessStrategy(const AbstractStorageDecl *storage) { switch (storage->getReadWriteImpl()) { case ReadWriteImplKind::Immutable: assert(isa<VarDecl>(storage) && cast<VarDecl>(storage)->isLet() && "mutation of a immutable variable that isn't a let"); return AccessStrategy::getStorage(); case ReadWriteImplKind::Stored: return AccessStrategy::getStorage(); case ReadWriteImplKind::MaterializeForSet: return AccessStrategy::getAccessor(AccessorKind::MaterializeForSet, /*dispatch*/ false); case ReadWriteImplKind::MutableAddress: return AccessStrategy::getAccessor(AccessorKind::MutableAddress, /*dispatch*/ false); case ReadWriteImplKind::Modify: return AccessStrategy::getAccessor(AccessorKind::Modify, /*dispatch*/ false); case ReadWriteImplKind::MaterializeToTemporary: return AccessStrategy::getMaterializeToTemporary( getDirectReadAccessStrategy(storage), getDirectWriteAccessStrategy(storage)); } llvm_unreachable("bad impl kind"); } static AccessStrategy getOpaqueReadAccessStrategy(const AbstractStorageDecl *storage, bool dispatch) { return AccessStrategy::getAccessor(AccessorKind::Get, dispatch); } static AccessStrategy getOpaqueWriteAccessStrategy(const AbstractStorageDecl *storage, bool dispatch){ return AccessStrategy::getAccessor(AccessorKind::Set, dispatch); } static bool hasDispatchedMaterializeForSet(const AbstractStorageDecl *storage) { // If the declaration is dynamic, there's no materializeForSet. if (storage->isDynamic()) return false; // If the declaration was imported from C, we won't gain anything // from using materializeForSet, and furthermore, it might not // exist. if (storage->hasClangNode()) return false; // If the declaration is not in type context, there's no // materializeForSet. auto dc = storage->getDeclContext(); if (!dc->isTypeContext()) return false; // @objc protocols count also don't have materializeForSet declarations. if (auto proto = dyn_cast<ProtocolDecl>(dc)) { if (proto->isObjC()) return false; } // Otherwise it should have a materializeForSet if we might be // accessing it opaquely. return true; } static AccessStrategy getOpaqueAccessStrategy(const AbstractStorageDecl *storage, AccessKind accessKind, bool dispatch) { switch (accessKind) { case AccessKind::Read: return getOpaqueReadAccessStrategy(storage, dispatch); case AccessKind::Write: return getOpaqueWriteAccessStrategy(storage, dispatch); case AccessKind::ReadWrite: if (hasDispatchedMaterializeForSet(storage)) return AccessStrategy::getAccessor(AccessorKind::MaterializeForSet, dispatch); return AccessStrategy::getMaterializeToTemporary( getOpaqueReadAccessStrategy(storage, dispatch), getOpaqueWriteAccessStrategy(storage, dispatch)); } llvm_unreachable("bad access kind"); } AccessStrategy AbstractStorageDecl::getAccessStrategy(AccessSemantics semantics, AccessKind accessKind, DeclContext *accessFromDC) const { switch (semantics) { case AccessSemantics::DirectToStorage: assert(hasStorage()); return AccessStrategy::getStorage(); case AccessSemantics::Ordinary: // Skip these checks for local variables, both because they're unnecessary // and because we won't necessarily have computed access. if (!getDeclContext()->isLocalContext()) { // If the property is defined in a non-final class or a protocol, the // accessors are dynamically dispatched, and we cannot do direct access. if (isPolymorphic(this)) return getOpaqueAccessStrategy(this, accessKind, /*dispatch*/ true); // If the storage is resilient to the given use DC (perhaps because // it's @_transparent and we have to be careful about it being inlined // across module lines), we cannot use direct access. // If we end up here with a stored property of a type that's resilient // from some resilience domain, we cannot do direct access. // // As an optimization, we do want to perform direct accesses of stored // properties declared inside the same resilience domain as the access // context. // // This is done by using DirectToStorage semantics above, with the // understanding that the access semantics are with respect to the // resilience domain of the accessor's caller. bool resilient; if (accessFromDC) resilient = isResilient(accessFromDC->getParentModule(), accessFromDC->getResilienceExpansion()); else resilient = isResilient(); if (resilient) return getOpaqueAccessStrategy(this, accessKind, /*dispatch*/ false); } LLVM_FALLTHROUGH; case AccessSemantics::DirectToImplementation: switch (accessKind) { case AccessKind::Read: return getDirectReadAccessStrategy(this); case AccessKind::Write: return getDirectWriteAccessStrategy(this); case AccessKind::ReadWrite: return getDirectReadWriteAccessStrategy(this); } llvm_unreachable("bad access kind"); case AccessSemantics::BehaviorInitialization: // Behavior initialization writes to the property as if it has storage. // SIL definite initialization will introduce the logical accesses. // Reads or inouts go through the ordinary path. switch (accessKind) { case AccessKind::Write: return AccessStrategy::getBehaviorStorage(); case AccessKind::Read: case AccessKind::ReadWrite: return getAccessStrategy(AccessSemantics::Ordinary, accessKind, accessFromDC); } } llvm_unreachable("bad access semantics"); } bool AbstractStorageDecl::requiresMaterializeForSet() const { // Only for mutable storage. if (!supportsMutation()) return false; // We only need materializeForSet in type contexts. // TODO: resilient global variables? auto *dc = getDeclContext(); if (!dc->isTypeContext()) return false; // Requirements of ObjC protocols don't need materializeForSet. if (auto protoDecl = dyn_cast<ProtocolDecl>(dc)) if (protoDecl->isObjC()) return false; // Members of structs imported by Clang don't need an eagerly-synthesized // materializeForSet. if (auto structDecl = dyn_cast<StructDecl>(dc)) if (structDecl->hasClangNode()) return false; return true; } void AbstractStorageDecl::visitExpectedOpaqueAccessors( llvm::function_ref<void (AccessorKind)> visit) const { // For now, always assume storage declarations should have getters // instead of read accessors. visit(AccessorKind::Get); if (supportsMutation()) { // All mutable storage should have a setter. visit(AccessorKind::Set); // Include materializeForSet if necessary. if (requiresMaterializeForSet()) visit(AccessorKind::MaterializeForSet); } } void AbstractStorageDecl::visitOpaqueAccessors( llvm::function_ref<void (AccessorDecl*)> visit) const { visitExpectedOpaqueAccessors([&](AccessorKind kind) { auto accessor = getAccessor(kind); assert(accessor && "didn't have expected opaque accessor"); visit(accessor); }); } static bool hasPrivateOrFilePrivateFormalAccess(const ValueDecl *D) { return D->hasAccess() && D->getFormalAccess() <= AccessLevel::FilePrivate; } /// Returns true if one of the ancestor DeclContexts of this ValueDecl is either /// marked private or fileprivate or is a local context. static bool isInPrivateOrLocalContext(const ValueDecl *D) { const DeclContext *DC = D->getDeclContext(); if (!DC->isTypeContext()) { assert((DC->isModuleScopeContext() || DC->isLocalContext()) && "unexpected context kind"); return DC->isLocalContext(); } auto *nominal = DC->getAsNominalTypeOrNominalTypeExtensionContext(); if (nominal == nullptr) return false; if (hasPrivateOrFilePrivateFormalAccess(nominal)) return true; return isInPrivateOrLocalContext(nominal); } bool ValueDecl::isOutermostPrivateOrFilePrivateScope() const { return hasPrivateOrFilePrivateFormalAccess(this) && !isInPrivateOrLocalContext(this); } bool AbstractStorageDecl::isFormallyResilient() const { // Check for an explicit @_fixed_layout attribute. if (getAttrs().hasAttribute<FixedLayoutAttr>()) return false; // Private and (unversioned) internal variables always have a // fixed layout. if (!getFormalAccessScope(/*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true).isPublic()) return false; // If we're an instance property of a nominal type, query the type. auto *dc = getDeclContext(); if (!isStatic()) if (auto *nominalDecl = dc->getAsNominalTypeOrNominalTypeExtensionContext()) return nominalDecl->isResilient(); return true; } bool AbstractStorageDecl::isResilient() const { if (!isFormallyResilient()) return false; switch (getDeclContext()->getParentModule()->getResilienceStrategy()) { case ResilienceStrategy::Resilient: return true; case ResilienceStrategy::Default: return false; } llvm_unreachable("Unhandled ResilienceStrategy in switch."); } bool AbstractStorageDecl::isResilient(ModuleDecl *M, ResilienceExpansion expansion) const { switch (expansion) { case ResilienceExpansion::Minimal: return isResilient(); case ResilienceExpansion::Maximal: return isResilient() && M != getModuleContext(); } llvm_unreachable("bad resilience expansion"); } bool ValueDecl::isInstanceMember() const { DeclContext *DC = getDeclContext(); if (!DC->isTypeContext()) return false; switch (getKind()) { case DeclKind::Import: case DeclKind::Extension: case DeclKind::PatternBinding: case DeclKind::EnumCase: case DeclKind::TopLevelCode: case DeclKind::InfixOperator: case DeclKind::PrefixOperator: case DeclKind::PostfixOperator: case DeclKind::IfConfig: case DeclKind::PoundDiagnostic: case DeclKind::PrecedenceGroup: case DeclKind::MissingMember: llvm_unreachable("Not a ValueDecl"); case DeclKind::Class: case DeclKind::Enum: case DeclKind::Protocol: case DeclKind::Struct: case DeclKind::TypeAlias: case DeclKind::GenericTypeParam: case DeclKind::AssociatedType: // Types are not instance members. return false; case DeclKind::Constructor: // Constructors are not instance members. return false; case DeclKind::Destructor: // Destructors are technically instance members, although they // can't actually be referenced as such. return true; case DeclKind::Func: case DeclKind::Accessor: // Non-static methods are instance members. return !cast<FuncDecl>(this)->isStatic(); case DeclKind::EnumElement: case DeclKind::Param: // enum elements and function parameters are not instance members. return false; case DeclKind::Subscript: // Subscripts are always instance members. return true; case DeclKind::Var: // Non-static variables are instance members. return !cast<VarDecl>(this)->isStatic(); case DeclKind::Module: // Modules are never instance members. return false; } llvm_unreachable("bad DeclKind"); } unsigned ValueDecl::getLocalDiscriminator() const { return LocalDiscriminator; } void ValueDecl::setLocalDiscriminator(unsigned index) { assert(getDeclContext()->isLocalContext()); assert(LocalDiscriminator == 0 && "LocalDiscriminator is set multiple times"); LocalDiscriminator = index; } ValueDecl *ValueDecl::getOverriddenDecl() const { auto overridden = getOverriddenDecls(); if (overridden.empty()) return nullptr; // FIXME: Arbitrarily pick the first overridden declaration. return overridden.front(); } bool ValueDecl::overriddenDeclsComputed() const { return LazySemanticInfo.hasOverriddenComputed; } bool swift::conflicting(const OverloadSignature& sig1, const OverloadSignature& sig2, bool skipProtocolExtensionCheck) { // A member of a protocol extension never conflicts with a member of a // protocol. if (!skipProtocolExtensionCheck && sig1.InProtocolExtension != sig2.InProtocolExtension) return false; // If the base names are different, they can't conflict. if (sig1.Name.getBaseName() != sig2.Name.getBaseName()) return false; // If one is an operator and the other is not, they can't conflict. if (sig1.UnaryOperator != sig2.UnaryOperator) return false; // If one is an instance and the other is not, they can't conflict. if (sig1.IsInstanceMember != sig2.IsInstanceMember) return false; // If one is a compound name and the other is not, they do not conflict // if one is a property and the other is a non-nullary function. if (sig1.Name.isCompoundName() != sig2.Name.isCompoundName()) { return !((sig1.IsVariable && !sig2.Name.getArgumentNames().empty()) || (sig2.IsVariable && !sig1.Name.getArgumentNames().empty())); } return sig1.Name == sig2.Name; } bool swift::conflicting(ASTContext &ctx, const OverloadSignature& sig1, CanType sig1Type, const OverloadSignature& sig2, CanType sig2Type, bool *wouldConflictInSwift5, bool skipProtocolExtensionCheck) { // If the signatures don't conflict to begin with, we're done. if (!conflicting(sig1, sig2, skipProtocolExtensionCheck)) return false; // Functions always conflict with non-functions with the same signature. // In practice, this only applies for zero argument functions. if (sig1.IsFunction != sig2.IsFunction) return true; // Variables always conflict with non-variables with the same signature. // (e.g variables with zero argument functions, variables with type // declarations) if (sig1.IsVariable != sig2.IsVariable) { // Prior to Swift 5, we permitted redeclarations of variables as different // declarations if the variable was declared in an extension of a generic // type. Make sure we maintain this behaviour in versions < 5. if (!ctx.isSwiftVersionAtLeast(5)) { if ((sig1.IsVariable && sig1.InExtensionOfGenericType) || (sig2.IsVariable && sig2.InExtensionOfGenericType)) { if (wouldConflictInSwift5) *wouldConflictInSwift5 = true; return false; } } return true; } // Otherwise, the declarations conflict if the overload types are the same. if (sig1Type != sig2Type) return false; // The Swift 5 overload types are the same, but similar to the above, prior to // Swift 5, a variable not in an extension of a generic type got a null // overload type instead of a function type as it does now, so we really // follow that behaviour and warn if there's going to be a conflict in future. if (!ctx.isSwiftVersionAtLeast(5)) { auto swift4Sig1Type = sig1.IsVariable && !sig1.InExtensionOfGenericType ? CanType() : sig1Type; auto swift4Sig2Type = sig1.IsVariable && !sig2.InExtensionOfGenericType ? CanType() : sig1Type; if (swift4Sig1Type != swift4Sig2Type) { // Old was different to the new behaviour! if (wouldConflictInSwift5) *wouldConflictInSwift5 = true; return false; } } return true; } static Type mapSignatureFunctionType(ASTContext &ctx, Type type, bool topLevelFunction, bool isMethod, bool isInitializer, unsigned curryLevels); /// Map a type within the signature of a declaration. static Type mapSignatureType(ASTContext &ctx, Type type) { return type.transform([&](Type type) -> Type { if (type->is<FunctionType>()) { return mapSignatureFunctionType(ctx, type, false, false, false, 1); } return type; }); } /// Map a signature type for a parameter. static Type mapSignatureParamType(ASTContext &ctx, Type type) { return mapSignatureType(ctx, type); } /// Map an ExtInfo for a function type. /// /// When checking if two signatures should be equivalent for overloading, /// we may need to compare the extended information. /// /// In the type of the function declaration, none of the extended information /// is relevant. We cannot overload purely on 'throws' or the calling /// convention of the declaration itself. /// /// For function parameter types, we do want to be able to overload on /// 'throws', since that is part of the mangled symbol name, but not /// @noescape. static AnyFunctionType::ExtInfo mapSignatureExtInfo(AnyFunctionType::ExtInfo info, bool topLevelFunction) { if (topLevelFunction) return AnyFunctionType::ExtInfo(); return AnyFunctionType::ExtInfo() .withRepresentation(info.getRepresentation()) .withIsAutoClosure(info.isAutoClosure()) .withThrows(info.throws()); } /// Map a function's type to the type used for computing signatures, /// which involves stripping some attributes, stripping default arguments, /// transforming implicitly unwrapped optionals into strict optionals, /// stripping 'inout' on the 'self' parameter etc. static Type mapSignatureFunctionType(ASTContext &ctx, Type type, bool topLevelFunction, bool isMethod, bool isInitializer, unsigned curryLevels) { if (curryLevels == 0) { // In an initializer, ignore optionality. if (isInitializer) { if (auto inOutTy = type->getAs<InOutType>()) { if (auto objectType = inOutTy->getObjectType()->getOptionalObjectType()) { type = InOutType::get(objectType); } } else if (auto objectType = type->getOptionalObjectType()) { type = objectType; } } return mapSignatureParamType(ctx, type); } auto funcTy = type->castTo<AnyFunctionType>(); SmallVector<AnyFunctionType::Param, 4> newParams; for (const auto &param : funcTy->getParams()) { auto newParamType = mapSignatureParamType(ctx, param.getType()); ParameterTypeFlags newFlags = param.getParameterFlags().withEscaping(false); // For the 'self' of a method, strip off 'inout'. if (isMethod) { newFlags = newFlags.withInOut(false); } AnyFunctionType::Param newParam(newParamType->getInOutObjectType(), param.getLabel(), newFlags); newParams.push_back(newParam); } // Map the result type. auto resultTy = mapSignatureFunctionType( ctx, funcTy->getResult(), topLevelFunction, false, isInitializer, curryLevels - 1); // Map various attributes differently depending on if we're looking at // the declaration, or a function parameter type. AnyFunctionType::ExtInfo info = mapSignatureExtInfo( funcTy->getExtInfo(), topLevelFunction); // Rebuild the resulting function type. if (auto genericFuncTy = dyn_cast<GenericFunctionType>(funcTy)) return GenericFunctionType::get(genericFuncTy->getGenericSignature(), newParams, resultTy, info); return FunctionType::get(newParams, resultTy, info); } OverloadSignature ValueDecl::getOverloadSignature() const { OverloadSignature signature; signature.Name = getFullName(); signature.InProtocolExtension = static_cast<bool>(getDeclContext()->getAsProtocolExtensionContext()); signature.IsInstanceMember = isInstanceMember(); signature.IsVariable = isa<VarDecl>(this); signature.IsFunction = isa<AbstractFunctionDecl>(this); // Unary operators also include prefix/postfix. if (auto func = dyn_cast<FuncDecl>(this)) { if (func->isUnaryOperator()) { signature.UnaryOperator = func->getAttrs().getUnaryOperatorKind(); } } if (auto *extension = dyn_cast<ExtensionDecl>(getDeclContext())) if (extension->isGeneric()) signature.InExtensionOfGenericType = true; return signature; } CanType ValueDecl::getOverloadSignatureType() const { if (auto *afd = dyn_cast<AbstractFunctionDecl>(this)) { bool isMethod = afd->hasImplicitSelfDecl(); return mapSignatureFunctionType( getASTContext(), getInterfaceType(), /*topLevelFunction=*/true, isMethod, /*isInitializer=*/isa<ConstructorDecl>(afd), isMethod ? 2 : 1)->getCanonicalType(); } if (auto *asd = dyn_cast<AbstractStorageDecl>(this)) { // First, get the default overload signature type for the decl. For vars, // this is the empty tuple type, as variables cannot be overloaded directly // by type. For subscripts, it's their interface type. CanType defaultSignatureType; if (isa<VarDecl>(this)) { defaultSignatureType = TupleType::getEmpty(getASTContext()); } else { defaultSignatureType = getInterfaceType()->getCanonicalType(); } // We want to curry the default signature type with the 'self' type of the // given context (if any) in order to ensure the overload signature type // is unique across different contexts, such as between a protocol extension // and struct decl. return defaultSignatureType->addCurriedSelfType(getDeclContext()) ->getCanonicalType(); } // Note: If you add more cases to this function, you should update the // implementation of the swift::conflicting overload that deals with // overload types, in order to account for cases where the overload types // don't match, but the decls differ and therefore always conflict. return CanType(); } llvm::TinyPtrVector<ValueDecl *> ValueDecl::getOverriddenDecls() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(OverriddenDeclsRequest{const_cast<ValueDecl *>(this)}); } void ValueDecl::setOverriddenDecls(ArrayRef<ValueDecl *> overridden) { llvm::TinyPtrVector<ValueDecl *> overriddenVec(overridden); OverriddenDeclsRequest request{const_cast<ValueDecl *>(this)}; request.cacheResult(overriddenVec); } bool ValueDecl::isObjC() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(IsObjCRequest{const_cast<ValueDecl *>(this)}); } void ValueDecl::setIsObjC(bool value) { assert(!LazySemanticInfo.isObjCComputed || LazySemanticInfo.isObjC == value); if (LazySemanticInfo.isObjCComputed) { assert(LazySemanticInfo.isObjC == value); return; } LazySemanticInfo.isObjCComputed = true; LazySemanticInfo.isObjC = value; } bool ValueDecl::isDynamic() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(IsDynamicRequest{const_cast<ValueDecl *>(this)}); } void ValueDecl::setIsDynamic(bool value) { assert(!LazySemanticInfo.isDynamicComputed || LazySemanticInfo.isDynamic == value); if (LazySemanticInfo.isDynamicComputed) { assert(LazySemanticInfo.isDynamic == value); return; } LazySemanticInfo.isDynamicComputed = true; LazySemanticInfo.isDynamic = value; } bool ValueDecl::canBeAccessedByDynamicLookup() const { if (!hasName()) return false; // Dynamic lookup can only find class and protocol members, or extensions of // classes. auto nominalDC = getDeclContext()->getAsNominalTypeOrNominalTypeExtensionContext(); if (!nominalDC || (!isa<ClassDecl>(nominalDC) && !isa<ProtocolDecl>(nominalDC))) return false; // Dynamic lookup cannot find results within a non-protocol generic context, // because there is no sensible way to infer the generic arguments. if (getDeclContext()->isGenericContext() && !isa<ProtocolDecl>(nominalDC)) return false; // Dynamic lookup can find functions, variables, and subscripts. if (!isa<FuncDecl>(this) && !isa<VarDecl>(this) && !isa<SubscriptDecl>(this)) return false; // Dynamic lookup can only find @objc members. if (!isObjC()) return false; return true; } ArrayRef<ValueDecl *> ValueDecl::getSatisfiedProtocolRequirements(bool Sorted) const { // Dig out the nominal type. NominalTypeDecl *NTD = getDeclContext()->getAsNominalTypeOrNominalTypeExtensionContext(); if (!NTD || isa<ProtocolDecl>(NTD)) return {}; return NTD->getSatisfiedProtocolRequirementsForMember(this, Sorted); } bool ValueDecl::isProtocolRequirement() const { assert(isa<ProtocolDecl>(getDeclContext())); if (isa<AccessorDecl>(this) || isa<TypeAliasDecl>(this) || isa<NominalTypeDecl>(this)) return false; return true; } bool ValueDecl::hasInterfaceType() const { return !TypeAndAccess.getPointer().isNull(); } Type ValueDecl::getInterfaceType() const { assert(hasInterfaceType() && "No interface type was set"); return TypeAndAccess.getPointer(); } void ValueDecl::setInterfaceType(Type type) { if (!type.isNull()) { assert(!type->hasTypeVariable() && "Type variable in interface type"); if (isa<ParamDecl>(this)) assert(!type->is<InOutType>() && "caller did not pass a base type"); } // lldb creates global typealiases with archetypes in them. // FIXME: Add an isDebugAlias() flag, like isDebugVar(). // // Also, ParamDecls in closure contexts can have type variables // archetype in them during constraint generation. if (!type.isNull() && !isa<TypeAliasDecl>(this) && !(isa<ParamDecl>(this) && isa<AbstractClosureExpr>(getDeclContext()))) { assert(!type->hasArchetype() && "Archetype in interface type"); } TypeAndAccess.setPointer(type); } bool ValueDecl::hasValidSignature() const { if (!hasInterfaceType()) return false; // FIXME -- The build blows up if the correct code is used: // return getValidationState() > ValidationState::CheckingWithValidSignature; return getValidationState() != ValidationState::Checking; } Optional<ObjCSelector> ValueDecl::getObjCRuntimeName() const { if (auto func = dyn_cast<AbstractFunctionDecl>(this)) return func->getObjCSelector(); ASTContext &ctx = getASTContext(); auto makeSelector = [&](Identifier name) -> ObjCSelector { return ObjCSelector(ctx, 0, { name }); }; if (auto classDecl = dyn_cast<ClassDecl>(this)) { SmallString<32> scratch; return makeSelector( ctx.getIdentifier(classDecl->getObjCRuntimeName(scratch))); } if (auto protocol = dyn_cast<ProtocolDecl>(this)) { SmallString<32> scratch; return makeSelector( ctx.getIdentifier(protocol->getObjCRuntimeName(scratch))); } if (auto var = dyn_cast<VarDecl>(this)) return makeSelector(var->getObjCPropertyName()); return None; } bool ValueDecl::canInferObjCFromRequirement(ValueDecl *requirement) { // Only makes sense for a requirement of an @objc protocol. auto proto = cast<ProtocolDecl>(requirement->getDeclContext()); if (!proto->isObjC()) return false; // Only makes sense when this declaration is within a nominal type // or extension thereof. auto nominal = getDeclContext()->getAsNominalTypeOrNominalTypeExtensionContext(); if (!nominal) return false; // If there is already an @objc attribute with an explicit name, we // can't infer a name (it's already there). if (auto objcAttr = getAttrs().getAttribute<ObjCAttr>()) { if (!objcAttr->isNameImplicit()) return false; } // If the nominal type doesn't conform to the protocol at all, we // cannot infer @objc no matter what we do. SmallVector<ProtocolConformance *, 1> conformances; if (!nominal->lookupConformance(getModuleContext(), proto, conformances)) return false; // If any of the conformances is attributed to the context in which // this declaration resides, we can infer @objc or the Objective-C // name. auto dc = getDeclContext(); for (auto conformance : conformances) { if (conformance->getDeclContext() == dc) return true; } // Nothing to infer from. return false; } SourceLoc ValueDecl::getAttributeInsertionLoc(bool forModifier) const { if (isImplicit()) return SourceLoc(); if (auto var = dyn_cast<VarDecl>(this)) { // [attrs] var ... // The attributes are part of the VarDecl, but the 'var' is part of the PBD. SourceLoc resultLoc = var->getAttrs().getStartLoc(forModifier); if (resultLoc.isValid()) { return resultLoc; } else if (auto pbd = var->getParentPatternBinding()) { return pbd->getStartLoc(); } else { return var->getStartLoc(); } } SourceLoc resultLoc = getAttrs().getStartLoc(forModifier); return resultLoc.isValid() ? resultLoc : getStartLoc(); } /// Returns true if \p VD needs to be treated as publicly-accessible /// at the SIL, LLVM, and machine levels due to being @usableFromInline. bool ValueDecl::isUsableFromInline() const { assert(getFormalAccess() == AccessLevel::Internal); if (getAttrs().hasAttribute<UsableFromInlineAttr>() || getAttrs().hasAttribute<InlinableAttr>()) return true; if (auto *accessor = dyn_cast<AccessorDecl>(this)) { auto *storage = accessor->getStorage(); if (storage->getAttrs().hasAttribute<UsableFromInlineAttr>() || storage->getAttrs().hasAttribute<InlinableAttr>()) return true; } if (auto *EED = dyn_cast<EnumElementDecl>(this)) if (EED->getParentEnum()->getAttrs().hasAttribute<UsableFromInlineAttr>()) return true; if (auto *ATD = dyn_cast<AssociatedTypeDecl>(this)) if (ATD->getProtocol()->getAttrs().hasAttribute<UsableFromInlineAttr>()) return true; return false; } /// Return the access level of an internal or public declaration /// that's been testably imported. static AccessLevel getTestableAccess(const ValueDecl *decl) { // Non-final classes are considered open to @testable importers. if (auto cls = dyn_cast<ClassDecl>(decl)) { if (!cls->isFinal()) return AccessLevel::Open; // Non-final overridable class members are considered open to // @testable importers. } else if (decl->isPotentiallyOverridable()) { if (!cast<ValueDecl>(decl)->isFinal()) return AccessLevel::Open; } // Everything else is considered public. return AccessLevel::Public; } /// Adjust \p access based on whether \p VD is \@usableFromInline or has been /// testably imported from \p useDC. /// /// \p access isn't always just `VD->getFormalAccess()` because this adjustment /// may be for a write, in which case the setter's access might be used instead. static AccessLevel getAdjustedFormalAccess(const ValueDecl *VD, AccessLevel access, const DeclContext *useDC, bool treatUsableFromInlineAsPublic) { if (treatUsableFromInlineAsPublic && access == AccessLevel::Internal && VD->isUsableFromInline()) { return AccessLevel::Public; } if (useDC && (access == AccessLevel::Internal || access == AccessLevel::Public)) { if (auto *useSF = dyn_cast<SourceFile>(useDC->getModuleScopeContext())) if (useSF->hasTestableImport(VD->getModuleContext())) return getTestableAccess(VD); } return access; } /// Convenience overload that uses `VD->getFormalAccess()` as the access to /// adjust. static AccessLevel getAdjustedFormalAccess(const ValueDecl *VD, const DeclContext *useDC, bool treatUsableFromInlineAsPublic) { return getAdjustedFormalAccess(VD, VD->getFormalAccess(), useDC, treatUsableFromInlineAsPublic); } AccessLevel ValueDecl::getEffectiveAccess() const { auto effectiveAccess = getAdjustedFormalAccess(this, /*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true); // Handle @testable. switch (effectiveAccess) { case AccessLevel::Open: break; case AccessLevel::Public: case AccessLevel::Internal: if (getModuleContext()->isTestingEnabled()) effectiveAccess = getTestableAccess(this); break; case AccessLevel::FilePrivate: break; case AccessLevel::Private: effectiveAccess = AccessLevel::FilePrivate; break; } auto restrictToEnclosing = [this](AccessLevel effectiveAccess, AccessLevel enclosingAccess) -> AccessLevel{ if (effectiveAccess == AccessLevel::Open && enclosingAccess == AccessLevel::Public && isa<NominalTypeDecl>(this)) { // Special case: an open class may be contained in a public // class/struct/enum. Leave effectiveAccess as is. return effectiveAccess; } return std::min(effectiveAccess, enclosingAccess); }; if (auto enclosingNominal = dyn_cast<NominalTypeDecl>(getDeclContext())) { effectiveAccess = restrictToEnclosing(effectiveAccess, enclosingNominal->getEffectiveAccess()); } else if (auto enclosingExt = dyn_cast<ExtensionDecl>(getDeclContext())) { // Just check the base type. If it's a constrained extension, Sema should // have already enforced access more strictly. if (auto nominal = enclosingExt->getExtendedNominal()) { effectiveAccess = restrictToEnclosing(effectiveAccess, nominal->getEffectiveAccess()); } } else if (getDeclContext()->isLocalContext()) { effectiveAccess = AccessLevel::FilePrivate; } return effectiveAccess; } AccessLevel ValueDecl::getFormalAccess() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(AccessLevelRequest{const_cast<ValueDecl *>(this)}); } bool ValueDecl::hasOpenAccess(const DeclContext *useDC) const { assert(isa<ClassDecl>(this) || isa<ConstructorDecl>(this) || isPotentiallyOverridable()); AccessLevel access = getAdjustedFormalAccess(this, useDC, /*treatUsableFromInlineAsPublic*/false); return access == AccessLevel::Open; } /// Given the formal access level for using \p VD, compute the scope where /// \p VD may be accessed, taking \@usableFromInline, \@testable imports, /// and enclosing access levels into account. /// /// \p access isn't always just `VD->getFormalAccess()` because this adjustment /// may be for a write, in which case the setter's access might be used instead. static AccessScope getAccessScopeForFormalAccess(const ValueDecl *VD, AccessLevel formalAccess, const DeclContext *useDC, bool treatUsableFromInlineAsPublic) { AccessLevel access = getAdjustedFormalAccess(VD, formalAccess, useDC, treatUsableFromInlineAsPublic); const DeclContext *resultDC = VD->getDeclContext(); while (!resultDC->isModuleScopeContext()) { if (resultDC->isLocalContext() || access == AccessLevel::Private) return AccessScope(resultDC, /*private*/true); if (auto enclosingNominal = dyn_cast<NominalTypeDecl>(resultDC)) { auto enclosingAccess = getAdjustedFormalAccess(enclosingNominal, useDC, treatUsableFromInlineAsPublic); access = std::min(access, enclosingAccess); } else if (auto enclosingExt = dyn_cast<ExtensionDecl>(resultDC)) { // Just check the base type. If it's a constrained extension, Sema should // have already enforced access more strictly. if (auto nominal = enclosingExt->getExtendedNominal()) { auto nominalAccess = getAdjustedFormalAccess(nominal, useDC, treatUsableFromInlineAsPublic); access = std::min(access, nominalAccess); } } else { llvm_unreachable("unknown DeclContext kind"); } resultDC = resultDC->getParent(); } switch (access) { case AccessLevel::Private: case AccessLevel::FilePrivate: assert(resultDC->isModuleScopeContext()); return AccessScope(resultDC, access == AccessLevel::Private); case AccessLevel::Internal: return AccessScope(resultDC->getParentModule()); case AccessLevel::Public: case AccessLevel::Open: return AccessScope::getPublic(); } llvm_unreachable("unknown access level"); } AccessScope ValueDecl::getFormalAccessScope(const DeclContext *useDC, bool treatUsableFromInlineAsPublic) const { return getAccessScopeForFormalAccess(this, getFormalAccess(), useDC, treatUsableFromInlineAsPublic); } /// Checks if \p VD may be used from \p useDC, taking \@testable imports into /// account. /// /// Whenever the enclosing context of \p VD is usable from \p useDC, this /// should compute the same result as checkAccess, below, but more slowly. /// /// See ValueDecl::isAccessibleFrom for a description of \p forConformance. static bool checkAccessUsingAccessScopes(const DeclContext *useDC, const ValueDecl *VD, AccessLevel access) { AccessScope accessScope = getAccessScopeForFormalAccess(VD, access, useDC, /*treatUsableFromInlineAsPublic*/false); return accessScope.getDeclContext() == useDC || AccessScope(useDC).isChildOf(accessScope); } /// Checks if \p VD may be used from \p useDC, taking \@testable imports into /// account. /// /// When \p access is the same as `VD->getFormalAccess()` and the enclosing /// context of \p VD is usable from \p useDC, this ought to be the same as /// getting the AccessScope for `VD` and checking if \p useDC is within it. /// However, there's a source compatibility hack around protocol extensions /// that makes it not quite the same. /// /// See ValueDecl::isAccessibleFrom for a description of \p forConformance. static bool checkAccess(const DeclContext *useDC, const ValueDecl *VD, AccessLevel access, bool forConformance) { auto *sourceDC = VD->getDeclContext(); if (!forConformance) { if (auto *proto = sourceDC->getAsProtocolOrProtocolExtensionContext()) { // FIXME: Swift 4.1 allowed accessing protocol extension methods that were // marked 'public' if the protocol was '@_versioned' (now // '@usableFromInline'). Which works at the ABI level, so let's keep // supporting that here by explicitly checking for it. if (access == AccessLevel::Public && proto->getFormalAccess() == AccessLevel::Internal && proto->isUsableFromInline()) { return true; } // Skip the fast path below and just compare access scopes. return checkAccessUsingAccessScopes(useDC, VD, access); } } // Fast path: assume that the client context already has access to our parent // DeclContext, and only check what might be different about this declaration. if (!useDC) return access >= AccessLevel::Public; switch (access) { case AccessLevel::Private: return (useDC == sourceDC || AccessScope::allowsPrivateAccess(useDC, sourceDC)); case AccessLevel::FilePrivate: return useDC->getModuleScopeContext() == sourceDC->getModuleScopeContext(); case AccessLevel::Internal: { const ModuleDecl *sourceModule = sourceDC->getParentModule(); const DeclContext *useFile = useDC->getModuleScopeContext(); if (useFile->getParentModule() == sourceModule) return true; if (auto *useSF = dyn_cast<SourceFile>(useFile)) if (useSF->hasTestableImport(sourceModule)) return true; return false; } case AccessLevel::Public: case AccessLevel::Open: return true; } llvm_unreachable("bad access level"); } bool ValueDecl::isAccessibleFrom(const DeclContext *useDC, bool forConformance) const { auto access = getFormalAccess(); bool result = checkAccess(useDC, this, access, forConformance); // For everything outside of protocols and operators, we should get the same // result using either implementation of checkAccess, because useDC must // already have access to this declaration's DeclContext. // FIXME: Arguably, we're doing the wrong thing for operators here too, // because we're finding internal operators within private types. Fortunately // we have a requirement that a member operator take the enclosing type as an // argument, so it won't ever match. assert(getDeclContext()->getAsProtocolOrProtocolExtensionContext() || isOperator() || result == checkAccessUsingAccessScopes(useDC, this, access)); return result; } bool AbstractStorageDecl::isSetterAccessibleFrom(const DeclContext *DC, bool forConformance) const { assert(isSettable(DC)); // If a stored property does not have a setter, it is still settable from the // designated initializer constructor. In this case, don't check setter // access; it is not set. if (hasStorage() && !isSettable(nullptr)) return true; if (isa<ParamDecl>(this)) return true; auto access = getSetterFormalAccess(); return checkAccess(DC, this, access, forConformance); } void ValueDecl::copyFormalAccessFrom(const ValueDecl *source, bool sourceIsParentContext) { if (!hasAccess()) { AccessLevel access = source->getFormalAccess(); // To make something have the same access as a 'private' parent, it has to // be 'fileprivate' or greater. if (sourceIsParentContext && access == AccessLevel::Private) access = AccessLevel::FilePrivate; // Only certain declarations can be 'open'. if (access == AccessLevel::Open && !isPotentiallyOverridable()) { assert(!isa<ClassDecl>(this) && "copying 'open' onto a class has complications"); access = AccessLevel::Public; } setAccess(access); } // Inherit the @usableFromInline attribute. if (source->getAttrs().hasAttribute<UsableFromInlineAttr>() && !getAttrs().hasAttribute<UsableFromInlineAttr>() && !getAttrs().hasAttribute<InlinableAttr>() && DeclAttribute::canAttributeAppearOnDecl(DAK_UsableFromInline, this)) { auto &ctx = getASTContext(); auto *clonedAttr = new (ctx) UsableFromInlineAttr(/*implicit=*/true); getAttrs().add(clonedAttr); } } Type TypeDecl::getInheritedType(unsigned index) const { ASTContext &ctx = getASTContext(); return ctx.evaluator(InheritedTypeRequest{const_cast<TypeDecl *>(this), index}); } Type TypeDecl::getDeclaredInterfaceType() const { if (auto *NTD = dyn_cast<NominalTypeDecl>(this)) return NTD->getDeclaredInterfaceType(); if (auto *ATD = dyn_cast<AssociatedTypeDecl>(this)) { auto &ctx = getASTContext(); auto selfTy = getDeclContext()->getSelfInterfaceType(); if (!selfTy) return ErrorType::get(ctx); return DependentMemberType::get( selfTy, const_cast<AssociatedTypeDecl *>(ATD)); } Type interfaceType = hasInterfaceType() ? getInterfaceType() : nullptr; if (interfaceType.isNull() || interfaceType->is<ErrorType>()) return interfaceType; if (isa<ModuleDecl>(this)) return interfaceType; return interfaceType->castTo<MetatypeType>()->getInstanceType(); } int TypeDecl::compare(const TypeDecl *type1, const TypeDecl *type2) { // Order based on the enclosing declaration. auto dc1 = type1->getDeclContext(); auto dc2 = type2->getDeclContext(); // Prefer lower depths. auto depth1 = dc1->getSemanticDepth(); auto depth2 = dc2->getSemanticDepth(); if (depth1 != depth2) return depth1 < depth2 ? -1 : +1; // Prefer module names earlier in the alphabet. if (dc1->isModuleScopeContext() && dc2->isModuleScopeContext()) { auto module1 = dc1->getParentModule(); auto module2 = dc2->getParentModule(); if (int result = module1->getName().str().compare(module2->getName().str())) return result; } auto nominal1 = dc1->getAsNominalTypeOrNominalTypeExtensionContext(); auto nominal2 = dc2->getAsNominalTypeOrNominalTypeExtensionContext(); if (static_cast<bool>(nominal1) != static_cast<bool>(nominal2)) { return static_cast<bool>(nominal1) ? -1 : +1; } if (nominal1 && nominal2) { if (int result = compare(nominal1, nominal2)) return result; } if (int result = type1->getBaseName().getIdentifier().str().compare( type2->getBaseName().getIdentifier().str())) return result; // Error case: two type declarations that cannot be distinguished. if (type1 < type2) return -1; if (type1 > type2) return +1; return 0; } bool NominalTypeDecl::isFormallyResilient() const { // Private and (unversioned) internal types always have a // fixed layout. if (!getFormalAccessScope(/*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true).isPublic()) return false; // Check for an explicit @_fixed_layout or @_frozen attribute. if (getAttrs().hasAttribute<FixedLayoutAttr>() || getAttrs().hasAttribute<FrozenAttr>()) { return false; } // Structs and enums imported from C *always* have a fixed layout. // We know their size, and pass them as values in SIL and IRGen. if (hasClangNode()) return false; // @objc enums and protocols always have a fixed layout. if ((isa<EnumDecl>(this) || isa<ProtocolDecl>(this)) && isObjC()) return false; // Otherwise, the declaration behaves as if it was accessed via indirect // "resilient" interfaces, even if the module is not built with resilience. return true; } bool NominalTypeDecl::isResilient() const { // If we're not formally resilient, don't check the module resilience // strategy. if (!isFormallyResilient()) return false; // Otherwise, check the module. switch (getParentModule()->getResilienceStrategy()) { case ResilienceStrategy::Resilient: return true; case ResilienceStrategy::Default: return false; } llvm_unreachable("Unhandled ResilienceStrategy in switch."); } bool NominalTypeDecl::isResilient(ModuleDecl *M, ResilienceExpansion expansion) const { switch (expansion) { case ResilienceExpansion::Minimal: return isResilient(); case ResilienceExpansion::Maximal: return isResilient() && M != getModuleContext(); } llvm_unreachable("bad resilience expansion"); } void NominalTypeDecl::computeType() { assert(!hasInterfaceType()); ASTContext &ctx = getASTContext(); // A protocol has an implicit generic parameter list consisting of a single // generic parameter, Self, that conforms to the protocol itself. This // parameter is always implicitly bound. // // If this protocol has been deserialized, it already has generic parameters. // Don't add them again. if (auto proto = dyn_cast<ProtocolDecl>(this)) proto->createGenericParamsIfMissing(); Type declaredInterfaceTy = getDeclaredInterfaceType(); setInterfaceType(MetatypeType::get(declaredInterfaceTy, ctx)); if (declaredInterfaceTy->hasError()) setInvalid(); } enum class DeclTypeKind : unsigned { DeclaredType, DeclaredTypeInContext, DeclaredInterfaceType }; static Type computeNominalType(NominalTypeDecl *decl, DeclTypeKind kind) { ASTContext &ctx = decl->getASTContext(); // Handle the declared type in context. if (kind == DeclTypeKind::DeclaredTypeInContext) { auto interfaceType = computeNominalType(decl, DeclTypeKind::DeclaredInterfaceType); if (!decl->isGenericContext()) return interfaceType; auto *genericEnv = decl->getGenericEnvironmentOfContext(); return GenericEnvironment::mapTypeIntoContext( genericEnv, interfaceType); } // Get the parent type. Type Ty; DeclContext *dc = decl->getDeclContext(); if (dc->isTypeContext()) { switch (kind) { case DeclTypeKind::DeclaredType: { auto *nominal = dc->getAsNominalTypeOrNominalTypeExtensionContext(); if (nominal) Ty = nominal->getDeclaredType(); else Ty = ErrorType::get(ctx); break; } case DeclTypeKind::DeclaredTypeInContext: llvm_unreachable("Handled above"); case DeclTypeKind::DeclaredInterfaceType: Ty = dc->getDeclaredInterfaceType(); break; } if (!Ty) return Type(); if (Ty->is<ErrorType>()) Ty = Type(); } if (decl->getGenericParams() && !isa<ProtocolDecl>(decl)) { switch (kind) { case DeclTypeKind::DeclaredType: return UnboundGenericType::get(decl, Ty, ctx); case DeclTypeKind::DeclaredTypeInContext: llvm_unreachable("Handled above"); case DeclTypeKind::DeclaredInterfaceType: { // Note that here, we need to be able to produce a type // before the decl has been validated, so we rely on // the generic parameter list directly instead of looking // at the signature. SmallVector<Type, 4> args; for (auto param : decl->getGenericParams()->getParams()) args.push_back(param->getDeclaredInterfaceType()); return BoundGenericType::get(decl, Ty, args); } } llvm_unreachable("Unhandled DeclTypeKind in switch."); } else { return NominalType::get(decl, Ty, ctx); } } Type NominalTypeDecl::getDeclaredType() const { if (DeclaredTy) return DeclaredTy; auto *decl = const_cast<NominalTypeDecl *>(this); decl->DeclaredTy = computeNominalType(decl, DeclTypeKind::DeclaredType); return DeclaredTy; } Type NominalTypeDecl::getDeclaredTypeInContext() const { if (DeclaredTyInContext) return DeclaredTyInContext; auto *decl = const_cast<NominalTypeDecl *>(this); decl->DeclaredTyInContext = computeNominalType(decl, DeclTypeKind::DeclaredTypeInContext); return DeclaredTyInContext; } Type NominalTypeDecl::getDeclaredInterfaceType() const { if (DeclaredInterfaceTy) return DeclaredInterfaceTy; auto *decl = const_cast<NominalTypeDecl *>(this); decl->DeclaredInterfaceTy = computeNominalType(decl, DeclTypeKind::DeclaredInterfaceType); return DeclaredInterfaceTy; } void NominalTypeDecl::prepareExtensions() { // Types in local contexts can't have extensions if (getLocalContext() != nullptr) { return; } auto &context = Decl::getASTContext(); // If our list of extensions is out of date, update it now. if (context.getCurrentGeneration() > ExtensionGeneration) { unsigned previousGeneration = ExtensionGeneration; ExtensionGeneration = context.getCurrentGeneration(); context.loadExtensions(this, previousGeneration); } } ExtensionRange NominalTypeDecl::getExtensions() { prepareExtensions(); return ExtensionRange(ExtensionIterator(FirstExtension), ExtensionIterator()); } void NominalTypeDecl::addExtension(ExtensionDecl *extension) { assert(!extension->alreadyBoundToNominal() && "Already added extension"); extension->NextExtension.setInt(true); // First extension; set both first and last. if (!FirstExtension) { FirstExtension = extension; LastExtension = extension; return; } // Add to the end of the list. LastExtension->NextExtension.setPointer(extension); LastExtension = extension; } bool NominalTypeDecl::isOptionalDecl() const { return this == getASTContext().getOptionalDecl(); } GenericTypeDecl::GenericTypeDecl(DeclKind K, DeclContext *DC, Identifier name, SourceLoc nameLoc, MutableArrayRef<TypeLoc> inherited, GenericParamList *GenericParams) : GenericContext(DeclContextKind::GenericTypeDecl, DC), TypeDecl(K, DC, name, nameLoc, inherited) { setGenericParams(GenericParams); } TypeAliasDecl::TypeAliasDecl(SourceLoc TypeAliasLoc, SourceLoc EqualLoc, Identifier Name, SourceLoc NameLoc, GenericParamList *GenericParams, DeclContext *DC) : GenericTypeDecl(DeclKind::TypeAlias, DC, Name, NameLoc, {}, GenericParams), TypeAliasLoc(TypeAliasLoc), EqualLoc(EqualLoc) { Bits.TypeAliasDecl.IsCompatibilityAlias = false; Bits.TypeAliasDecl.IsDebuggerAlias = false; } SourceRange TypeAliasDecl::getSourceRange() const { auto TrailingWhereClauseSourceRange = getGenericTrailingWhereClauseSourceRange(); if (TrailingWhereClauseSourceRange.isValid()) return { TypeAliasLoc, TrailingWhereClauseSourceRange.End }; if (UnderlyingTy.hasLocation()) return { TypeAliasLoc, UnderlyingTy.getSourceRange().End }; return { TypeAliasLoc, getNameLoc() }; } void TypeAliasDecl::setUnderlyingType(Type underlying) { setValidationToChecked(); // lldb creates global typealiases containing archetypes // sometimes... if (underlying->hasArchetype() && isGenericContext()) underlying = underlying->mapTypeOutOfContext(); UnderlyingTy.setType(underlying); // FIXME -- if we already have an interface type, we're changing the // underlying type. See the comment in the ProtocolDecl case of // validateDecl(). if (!hasInterfaceType()) { // Set the interface type of this declaration. ASTContext &ctx = getASTContext(); // If we can set a sugared type, do so. if (!getGenericSignature()) { auto sugaredType = NameAliasType::get(this, Type(), SubstitutionMap(), underlying); setInterfaceType(MetatypeType::get(sugaredType, ctx)); } else { setInterfaceType(MetatypeType::get(underlying, ctx)); } } } UnboundGenericType *TypeAliasDecl::getUnboundGenericType() const { assert(getGenericParams()); Type parentTy; auto parentDC = getDeclContext(); if (auto nominal = parentDC->getAsNominalTypeOrNominalTypeExtensionContext()) parentTy = nominal->getDeclaredType(); return UnboundGenericType::get( const_cast<TypeAliasDecl *>(this), parentTy, getASTContext()); } Type AbstractTypeParamDecl::getSuperclass() const { auto *genericEnv = getDeclContext()->getGenericEnvironmentOfContext(); assert(genericEnv != nullptr && "Too much circularity"); auto contextTy = genericEnv->mapTypeIntoContext(getDeclaredInterfaceType()); if (auto *archetype = contextTy->getAs<ArchetypeType>()) return archetype->getSuperclass(); // FIXME: Assert that this is never queried. return nullptr; } ArrayRef<ProtocolDecl *> AbstractTypeParamDecl::getConformingProtocols() const { auto *genericEnv = getDeclContext()->getGenericEnvironmentOfContext(); assert(genericEnv != nullptr && "Too much circularity"); auto contextTy = genericEnv->mapTypeIntoContext(getDeclaredInterfaceType()); if (auto *archetype = contextTy->getAs<ArchetypeType>()) return archetype->getConformsTo(); // FIXME: Assert that this is never queried. return { }; } GenericTypeParamDecl::GenericTypeParamDecl(DeclContext *dc, Identifier name, SourceLoc nameLoc, unsigned depth, unsigned index) : AbstractTypeParamDecl(DeclKind::GenericTypeParam, dc, name, nameLoc) { Bits.GenericTypeParamDecl.Depth = depth; assert(Bits.GenericTypeParamDecl.Depth == depth && "Truncation"); Bits.GenericTypeParamDecl.Index = index; assert(Bits.GenericTypeParamDecl.Index == index && "Truncation"); auto &ctx = dc->getASTContext(); auto type = new (ctx, AllocationArena::Permanent) GenericTypeParamType(this); setInterfaceType(MetatypeType::get(type, ctx)); } SourceRange GenericTypeParamDecl::getSourceRange() const { SourceLoc endLoc = getNameLoc(); if (!getInherited().empty()) { endLoc = getInherited().back().getSourceRange().End; } return SourceRange(getNameLoc(), endLoc); } AssociatedTypeDecl::AssociatedTypeDecl(DeclContext *dc, SourceLoc keywordLoc, Identifier name, SourceLoc nameLoc, TypeLoc defaultDefinition, TrailingWhereClause *trailingWhere) : AbstractTypeParamDecl(DeclKind::AssociatedType, dc, name, nameLoc), KeywordLoc(keywordLoc), DefaultDefinition(defaultDefinition), TrailingWhere(trailingWhere) { } AssociatedTypeDecl::AssociatedTypeDecl(DeclContext *dc, SourceLoc keywordLoc, Identifier name, SourceLoc nameLoc, TrailingWhereClause *trailingWhere, LazyMemberLoader *definitionResolver, uint64_t resolverData) : AbstractTypeParamDecl(DeclKind::AssociatedType, dc, name, nameLoc), KeywordLoc(keywordLoc), TrailingWhere(trailingWhere), Resolver(definitionResolver), ResolverContextData(resolverData) { assert(Resolver && "missing resolver"); } void AssociatedTypeDecl::computeType() { assert(!hasInterfaceType()); auto &ctx = getASTContext(); auto interfaceTy = getDeclaredInterfaceType(); setInterfaceType(MetatypeType::get(interfaceTy, ctx)); } TypeLoc &AssociatedTypeDecl::getDefaultDefinitionLoc() { if (Resolver) { DefaultDefinition = Resolver->loadAssociatedTypeDefault(this, ResolverContextData); Resolver = nullptr; } return DefaultDefinition; } SourceRange AssociatedTypeDecl::getSourceRange() const { SourceLoc endLoc; if (auto TWC = getTrailingWhereClause()) endLoc = TWC->getSourceRange().End; else if (!getInherited().empty()) { endLoc = getInherited().back().getSourceRange().End; } else { endLoc = getNameLoc(); } return SourceRange(KeywordLoc, endLoc); } llvm::TinyPtrVector<AssociatedTypeDecl *> AssociatedTypeDecl::getOverriddenDecls() const { // FIXME: Performance hack because we end up looking at the overridden // declarations of an associated type a *lot*. OverriddenDeclsRequest request{const_cast<AssociatedTypeDecl *>(this)}; llvm::TinyPtrVector<ValueDecl *> overridden; if (auto cached = request.getCachedResult()) overridden = std::move(*cached); else overridden = AbstractTypeParamDecl::getOverriddenDecls(); llvm::TinyPtrVector<AssociatedTypeDecl *> assocTypes; for (auto decl : overridden) { assocTypes.push_back(cast<AssociatedTypeDecl>(decl)); } return assocTypes; } AssociatedTypeDecl *AssociatedTypeDecl::getAssociatedTypeAnchor() const { auto overridden = getOverriddenDecls(); // If this declaration does not override any other declarations, it's // the anchor. if (overridden.empty()) return const_cast<AssociatedTypeDecl *>(this); // Find the best anchor among the anchors of the overridden decls. AssociatedTypeDecl *bestAnchor = nullptr; for (auto assocType : overridden) { auto anchor = assocType->getAssociatedTypeAnchor(); if (!bestAnchor || compare(anchor, bestAnchor) < 0) bestAnchor = anchor; } return bestAnchor; } EnumDecl::EnumDecl(SourceLoc EnumLoc, Identifier Name, SourceLoc NameLoc, MutableArrayRef<TypeLoc> Inherited, GenericParamList *GenericParams, DeclContext *Parent) : NominalTypeDecl(DeclKind::Enum, Parent, Name, NameLoc, Inherited, GenericParams), EnumLoc(EnumLoc) { Bits.EnumDecl.Circularity = static_cast<unsigned>(CircularityCheck::Unchecked); Bits.EnumDecl.HasAssociatedValues = static_cast<unsigned>(AssociatedValueCheck::Unchecked); Bits.EnumDecl.HasAnyUnavailableValues = false; } Type EnumDecl::getRawType() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(EnumRawTypeRequest{const_cast<EnumDecl *>(this)}); } StructDecl::StructDecl(SourceLoc StructLoc, Identifier Name, SourceLoc NameLoc, MutableArrayRef<TypeLoc> Inherited, GenericParamList *GenericParams, DeclContext *Parent) : NominalTypeDecl(DeclKind::Struct, Parent, Name, NameLoc, Inherited, GenericParams), StructLoc(StructLoc) { Bits.StructDecl.HasUnreferenceableStorage = false; } ClassDecl::ClassDecl(SourceLoc ClassLoc, Identifier Name, SourceLoc NameLoc, MutableArrayRef<TypeLoc> Inherited, GenericParamList *GenericParams, DeclContext *Parent) : NominalTypeDecl(DeclKind::Class, Parent, Name, NameLoc, Inherited, GenericParams), ClassLoc(ClassLoc) { Bits.ClassDecl.Circularity = static_cast<unsigned>(CircularityCheck::Unchecked); Bits.ClassDecl.RequiresStoredPropertyInits = 0; Bits.ClassDecl.InheritsSuperclassInits = 0; Bits.ClassDecl.RawForeignKind = 0; Bits.ClassDecl.HasDestructorDecl = 0; Bits.ClassDecl.ObjCKind = 0; Bits.ClassDecl.HasMissingDesignatedInitializers = 0; Bits.ClassDecl.HasMissingVTableEntries = 0; } DestructorDecl *ClassDecl::getDestructor() { auto results = lookupDirect(DeclBaseName::createDestructor()); assert(!results.empty() && "Class without destructor?"); assert(results.size() == 1 && "More than one destructor?"); return cast<DestructorDecl>(results.front()); } void ClassDecl::addImplicitDestructor() { if (hasDestructor() || isInvalid()) return; auto *selfDecl = ParamDecl::createSelf(getLoc(), this); auto &ctx = getASTContext(); auto *DD = new (ctx) DestructorDecl(getLoc(), selfDecl, this); DD->setImplicit(); DD->setValidationToChecked(); // Create an empty body for the destructor. DD->setBody(BraceStmt::create(ctx, getLoc(), { }, getLoc(), true)); addMember(DD); setHasDestructor(); // Propagate access control and versioned-ness. DD->copyFormalAccessFrom(this, /*sourceIsParentContext*/true); // Wire up generic environment of DD. DD->setGenericEnvironment(getGenericEnvironmentOfContext()); // Mark DD as ObjC, as all dtors are. DD->setIsObjC(getASTContext().LangOpts.EnableObjCInterop); if (getASTContext().LangOpts.EnableObjCInterop) recordObjCMethod(DD); // Assign DD the interface type (Self) -> () -> () DD->computeType(); } bool ClassDecl::hasMissingDesignatedInitializers() const { auto *mutableThis = const_cast<ClassDecl *>(this); (void)mutableThis->lookupDirect(DeclBaseName::createConstructor(), /*ignoreNewExtensions*/true); return Bits.ClassDecl.HasMissingDesignatedInitializers; } bool ClassDecl::hasMissingVTableEntries() const { (void)getMembers(); return Bits.ClassDecl.HasMissingVTableEntries; } bool ClassDecl::inheritsSuperclassInitializers(LazyResolver *resolver) { // Check whether we already have a cached answer. if (addedImplicitInitializers()) return Bits.ClassDecl.InheritsSuperclassInits; // If there's no superclass, there's nothing to inherit. ClassDecl *superclassDecl; if (!(superclassDecl = getSuperclassDecl())) { setAddedImplicitInitializers(); return false; } // If the superclass has known-missing designated initializers, inheriting // is unsafe. if (superclassDecl->hasMissingDesignatedInitializers()) return false; // Otherwise, do all the work of resolving constructors, which will also // calculate the right answer. if (resolver == nullptr) resolver = getASTContext().getLazyResolver(); if (resolver) resolver->resolveImplicitConstructors(this); return Bits.ClassDecl.InheritsSuperclassInits; } ObjCClassKind ClassDecl::checkObjCAncestry() const { // See if we've already computed this. if (Bits.ClassDecl.ObjCKind) return ObjCClassKind(Bits.ClassDecl.ObjCKind - 1); llvm::SmallPtrSet<const ClassDecl *, 8> visited; bool genericAncestry = false, isObjC = false; const ClassDecl *CD = this; for (;;) { // If we hit circularity, we will diagnose at some point in typeCheckDecl(). // However we have to explicitly guard against that here because we get // called as part of validateDecl(). if (!visited.insert(CD).second) break; if (CD->isGenericContext()) genericAncestry = true; // Is this class @objc? For the current class, only look at the attribute // to avoid cycles; for superclasses, compute @objc completely. if ((CD == this && CD->getAttrs().hasAttribute<ObjCAttr>()) || (CD != this && CD->isObjC())) isObjC = true; if (!CD->hasSuperclass()) break; CD = CD->getSuperclassDecl(); // If we don't have a valid class here, we should have diagnosed // elsewhere. if (!CD) break; } ObjCClassKind kind = ObjCClassKind::ObjC; if (!isObjC) kind = ObjCClassKind::NonObjC; else if (genericAncestry) kind = ObjCClassKind::ObjCMembers; else if (CD == this || !CD->isObjC()) kind = ObjCClassKind::ObjCWithSwiftRoot; // Save the result for later. const_cast<ClassDecl *>(this)->Bits.ClassDecl.ObjCKind = unsigned(kind) + 1; return kind; } ClassDecl::MetaclassKind ClassDecl::getMetaclassKind() const { assert(getASTContext().LangOpts.EnableObjCInterop && "querying metaclass kind without objc interop"); auto objc = checkObjCAncestry() != ObjCClassKind::NonObjC; return objc ? MetaclassKind::ObjC : MetaclassKind::SwiftStub; } /// Mangle the name of a protocol or class for use in the Objective-C /// runtime. static StringRef mangleObjCRuntimeName(const NominalTypeDecl *nominal, llvm::SmallVectorImpl<char> &buffer) { { Mangle::ASTMangler Mangler; std::string MangledName = Mangler.mangleObjCRuntimeName(nominal); buffer.clear(); llvm::raw_svector_ostream os(buffer); os << MangledName; } assert(buffer.size() && "Invalid buffer size"); return StringRef(buffer.data(), buffer.size()); } StringRef ClassDecl::getObjCRuntimeName( llvm::SmallVectorImpl<char> &buffer) const { // If there is a Clang declaration, use it's runtime name. if (auto objcClass = dyn_cast_or_null<clang::ObjCInterfaceDecl>(getClangDecl())) return objcClass->getObjCRuntimeNameAsString(); // If there is an 'objc' attribute with a name, use that name. if (auto attr = getAttrs().getAttribute<ObjCRuntimeNameAttr>()) return attr->Name; if (auto objc = getAttrs().getAttribute<ObjCAttr>()) { if (auto name = objc->getName()) return name->getString(buffer); } // Produce the mangled name for this class. return mangleObjCRuntimeName(this, buffer); } ArtificialMainKind ClassDecl::getArtificialMainKind() const { if (getAttrs().hasAttribute<UIApplicationMainAttr>()) return ArtificialMainKind::UIApplicationMain; if (getAttrs().hasAttribute<NSApplicationMainAttr>()) return ArtificialMainKind::NSApplicationMain; llvm_unreachable("class has no @ApplicationMain attr?!"); } AbstractFunctionDecl * ClassDecl::findOverridingDecl(const AbstractFunctionDecl *Method) const { auto Members = getMembers(); for (auto M : Members) { auto *CurMethod = dyn_cast<AbstractFunctionDecl>(M); if (!CurMethod) continue; if (CurMethod->isOverridingDecl(Method)) { return CurMethod; } } return nullptr; } bool AbstractFunctionDecl::isOverridingDecl( const AbstractFunctionDecl *Method) const { const AbstractFunctionDecl *CurMethod = this; while (CurMethod) { if (CurMethod == Method) return true; CurMethod = CurMethod->getOverriddenDecl(); } return false; } AbstractFunctionDecl * ClassDecl::findImplementingMethod(const AbstractFunctionDecl *Method) const { const ClassDecl *C = this; while (C) { auto Members = C->getMembers(); for (auto M : Members) { auto *CurMethod = dyn_cast<AbstractFunctionDecl>(M); if (!CurMethod) continue; if (Method == CurMethod) return CurMethod; if (CurMethod->isOverridingDecl(Method)) { // This class implements a method return CurMethod; } } // Check the superclass if (!C->hasSuperclass()) break; C = C->getSuperclassDecl(); } return nullptr; } ClassDecl *ClassDecl::getGenericAncestor() const { ClassDecl *current = const_cast<ClassDecl *>(this); while (current) { if (current->isGenericContext()) return current; current = current->getSuperclassDecl(); } return nullptr; } EnumCaseDecl *EnumCaseDecl::create(SourceLoc CaseLoc, ArrayRef<EnumElementDecl *> Elements, DeclContext *DC) { void *buf = DC->getASTContext() .Allocate(sizeof(EnumCaseDecl) + sizeof(EnumElementDecl*) * Elements.size(), alignof(EnumCaseDecl)); return ::new (buf) EnumCaseDecl(CaseLoc, Elements, DC); } EnumElementDecl *EnumDecl::getElement(Identifier Name) const { // FIXME: Linear search is not great for large enum decls. for (EnumElementDecl *Elt : getAllElements()) if (Elt->getName() == Name) return Elt; return nullptr; } bool EnumDecl::hasPotentiallyUnavailableCaseValue() const { switch (static_cast<AssociatedValueCheck>(Bits.EnumDecl.HasAssociatedValues)) { case AssociatedValueCheck::Unchecked: // Compute below this->hasOnlyCasesWithoutAssociatedValues(); LLVM_FALLTHROUGH; default: return static_cast<bool>(Bits.EnumDecl.HasAnyUnavailableValues); } } bool EnumDecl::hasOnlyCasesWithoutAssociatedValues() const { // Check whether we already have a cached answer. switch (static_cast<AssociatedValueCheck>( Bits.EnumDecl.HasAssociatedValues)) { case AssociatedValueCheck::Unchecked: // Compute below. break; case AssociatedValueCheck::NoAssociatedValues: return true; case AssociatedValueCheck::HasAssociatedValues: return false; } for (auto elt : getAllElements()) { for (auto Attr : elt->getAttrs()) { if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) { if (!AvAttr->isInvalid()) { const_cast<EnumDecl*>(this)->Bits.EnumDecl.HasAnyUnavailableValues = true; } } } if (elt->hasAssociatedValues()) { const_cast<EnumDecl*>(this)->Bits.EnumDecl.HasAssociatedValues = static_cast<unsigned>(AssociatedValueCheck::HasAssociatedValues); return false; } } const_cast<EnumDecl*>(this)->Bits.EnumDecl.HasAssociatedValues = static_cast<unsigned>(AssociatedValueCheck::NoAssociatedValues); return true; } bool EnumDecl::isFormallyExhaustive(const DeclContext *useDC) const { // Enums explicitly marked frozen are exhaustive. if (getAttrs().hasAttribute<FrozenAttr>()) return true; // Objective-C enums /not/ marked frozen are /not/ exhaustive. // Note: This implicitly holds @objc enums defined in Swift to a higher // standard! if (hasClangNode()) return false; // Non-imported enums in non-resilient modules are exhaustive. const ModuleDecl *containingModule = getModuleContext(); switch (containingModule->getResilienceStrategy()) { case ResilienceStrategy::Default: return true; case ResilienceStrategy::Resilient: break; } // Non-public, non-versioned enums are always exhaustive. AccessScope accessScope = getFormalAccessScope(/*useDC*/nullptr, /*respectVersioned*/true); if (!accessScope.isPublic()) return true; // All other checks are use-site specific; with no further information, the // enum must be treated non-exhaustively. if (!useDC) return false; // Enums in the same module as the use site are exhaustive /unless/ the use // site is inlinable. if (useDC->getParentModule() == containingModule) if (useDC->getResilienceExpansion() == ResilienceExpansion::Maximal) return true; // Testably imported enums are exhaustive, on the grounds that only the author // of the original library can import it testably. if (auto *useSF = dyn_cast<SourceFile>(useDC->getModuleScopeContext())) if (useSF->hasTestableImport(containingModule)) return true; // Otherwise, the enum is non-exhaustive. return false; } bool EnumDecl::isEffectivelyExhaustive(ModuleDecl *M, ResilienceExpansion expansion) const { // Generated Swift code commits to handling garbage values of @objc enums, // whether imported or not, to deal with C's loose rules around enums. // This covers both frozen and non-frozen @objc enums. if (isObjC()) return false; // Otherwise, the only non-exhaustive cases are those that don't have a fixed // layout. assert(isFormallyExhaustive(M) == !isResilient(M,ResilienceExpansion::Maximal) && "ignoring the effects of @inlinable, @testable, and @objc, " "these should match up"); return !isResilient(M, expansion); } ProtocolDecl::ProtocolDecl(DeclContext *DC, SourceLoc ProtocolLoc, SourceLoc NameLoc, Identifier Name, MutableArrayRef<TypeLoc> Inherited, TrailingWhereClause *TrailingWhere) : NominalTypeDecl(DeclKind::Protocol, DC, Name, NameLoc, Inherited, nullptr), ProtocolLoc(ProtocolLoc), TrailingWhere(TrailingWhere) { Bits.ProtocolDecl.RequiresClassValid = false; Bits.ProtocolDecl.RequiresClass = false; Bits.ProtocolDecl.ExistentialConformsToSelfValid = false; Bits.ProtocolDecl.ExistentialConformsToSelf = false; Bits.ProtocolDecl.Circularity = static_cast<unsigned>(CircularityCheck::Unchecked); Bits.ProtocolDecl.NumRequirementsInSignature = 0; Bits.ProtocolDecl.HasMissingRequirements = false; Bits.ProtocolDecl.KnownProtocol = 0; Bits.ProtocolDecl.ComputingInheritedProtocols = false; } llvm::TinyPtrVector<ProtocolDecl *> ProtocolDecl::getInheritedProtocols() const { llvm::TinyPtrVector<ProtocolDecl *> result; SmallPtrSet<const ProtocolDecl *, 4> known; known.insert(this); bool anyObject = false; for (const auto &found : getDirectlyInheritedNominalTypeDecls( const_cast<ProtocolDecl *>(this), anyObject)) { if (auto proto = dyn_cast<ProtocolDecl>(found.second)) { if (known.insert(proto).second) result.push_back(proto); } } // FIXME: ComputingInheritedProtocols is dynamically dead. return result; } llvm::TinyPtrVector<AssociatedTypeDecl *> ProtocolDecl::getAssociatedTypeMembers() const { llvm::TinyPtrVector<AssociatedTypeDecl *> result; if (!isObjC()) { for (auto member : getMembers()) { if (auto ATD = dyn_cast<AssociatedTypeDecl>(member)) { result.push_back(ATD); } } } return result; } Type ProtocolDecl::getSuperclass() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(SuperclassTypeRequest{const_cast<ProtocolDecl *>(this)}); } ClassDecl *ProtocolDecl::getSuperclassDecl() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(SuperclassDeclRequest{const_cast<ProtocolDecl *>(this)}); } void ProtocolDecl::setSuperclass(Type superclass) { assert((!superclass || !superclass->hasArchetype()) && "superclass must be interface type"); LazySemanticInfo.Superclass.setPointerAndInt(superclass, true); } bool ProtocolDecl::walkInheritedProtocols( llvm::function_ref<TypeWalker::Action(ProtocolDecl *)> fn) const { auto self = const_cast<ProtocolDecl *>(this); // Visit all of the inherited protocols. SmallPtrSet<ProtocolDecl *, 8> visited; SmallVector<ProtocolDecl *, 4> stack; stack.push_back(self); visited.insert(self); while (!stack.empty()) { // Pull the next protocol off the stack. auto proto = stack.back(); stack.pop_back(); switch (fn(proto)) { case TypeWalker::Action::Stop: return true; case TypeWalker::Action::Continue: // Add inherited protocols to the stack. for (auto inherited : proto->getInheritedProtocols()) { if (visited.insert(inherited).second) stack.push_back(inherited); } break; case TypeWalker::Action::SkipChildren: break; } } return false; } bool ProtocolDecl::inheritsFrom(const ProtocolDecl *super) const { if (this == super) return false; return walkInheritedProtocols([super](ProtocolDecl *inherited) { if (inherited == super) return TypeWalker::Action::Stop; return TypeWalker::Action::Continue; }); } bool ProtocolDecl::requiresClassSlow() { // Set this first to catch (invalid) circular inheritance. Bits.ProtocolDecl.RequiresClassValid = true; Bits.ProtocolDecl.RequiresClass = false; // Quick check: @objc protocols require a class. if (isObjC()) return Bits.ProtocolDecl.RequiresClass = true; // Determine the set of nominal types that this protocol inherits. bool anyObject = false; auto allInheritedNominals = getDirectlyInheritedNominalTypeDecls(this, anyObject); // Quick check: do we inherit AnyObject? if (anyObject) return Bits.ProtocolDecl.RequiresClass = true; // Look through all of the inherited nominals for a superclass or a // class-bound protocol. for (const auto &found : allInheritedNominals) { // Superclass bound. if (isa<ClassDecl>(found.second)) return Bits.ProtocolDecl.RequiresClass = true; // A protocol that might be class-constrained; if (auto proto = dyn_cast<ProtocolDecl>(found.second)) { if (proto->requiresClass()) return Bits.ProtocolDecl.RequiresClass = true; } } return Bits.ProtocolDecl.RequiresClass; } bool ProtocolDecl::existentialConformsToSelfSlow() { // Assume for now that the existential conforms to itself; this // prevents circularity issues. Bits.ProtocolDecl.ExistentialConformsToSelfValid = true; Bits.ProtocolDecl.ExistentialConformsToSelf = true; if (!isObjC()) { Bits.ProtocolDecl.ExistentialConformsToSelf = false; return false; } // Check whether this protocol conforms to itself. for (auto member : getMembers()) { if (member->isInvalid()) continue; if (auto vd = dyn_cast<ValueDecl>(member)) { if (!vd->isInstanceMember()) { // A protocol cannot conform to itself if it has static members. Bits.ProtocolDecl.ExistentialConformsToSelf = false; return false; } } } // Check whether any of the inherited protocols fail to conform to // themselves. for (auto proto : getInheritedProtocols()) { if (!proto->existentialConformsToSelf()) { Bits.ProtocolDecl.ExistentialConformsToSelf = false; return false; } } return true; } /// Classify usages of Self in the given type. static SelfReferenceKind findProtocolSelfReferences(const ProtocolDecl *proto, Type type, bool skipAssocTypes) { // Tuples preserve variance. if (auto tuple = type->getAs<TupleType>()) { auto kind = SelfReferenceKind::None(); for (auto &elt : tuple->getElements()) { kind |= findProtocolSelfReferences(proto, elt.getType(), skipAssocTypes); } return kind; } // Function preserve variance in the result type, and flip variance in // the parameter type. if (auto funcTy = type->getAs<AnyFunctionType>()) { auto inputKind = SelfReferenceKind::None(); for (auto &elt : funcTy->getParams()) { inputKind |= findProtocolSelfReferences(proto, elt.getType(), skipAssocTypes); } auto resultKind = findProtocolSelfReferences(proto, funcTy->getResult(), skipAssocTypes); auto kind = inputKind.flip(); kind |= resultKind; return kind; } // Metatypes preserve variance. if (auto metaTy = type->getAs<MetatypeType>()) { return findProtocolSelfReferences(proto, metaTy->getInstanceType(), skipAssocTypes); } // Optionals preserve variance. if (auto optType = type->getOptionalObjectType()) { return findProtocolSelfReferences(proto, optType, skipAssocTypes); } // DynamicSelfType preserves variance. // FIXME: This shouldn't ever appear in protocol requirement // signatures. if (auto selfType = type->getAs<DynamicSelfType>()) { return findProtocolSelfReferences(proto, selfType->getSelfType(), skipAssocTypes); } // InOut types are invariant. if (auto inOutType = type->getAs<InOutType>()) { if (findProtocolSelfReferences(proto, inOutType->getObjectType(), skipAssocTypes)) { return SelfReferenceKind::Other(); } } // Bound generic types are invariant. if (auto boundGenericType = type->getAs<BoundGenericType>()) { for (auto paramType : boundGenericType->getGenericArgs()) { if (findProtocolSelfReferences(proto, paramType, skipAssocTypes)) { return SelfReferenceKind::Other(); } } } // A direct reference to 'Self' is covariant. if (proto->getProtocolSelfType()->isEqual(type)) return SelfReferenceKind::Result(); // Special handling for associated types. if (!skipAssocTypes && type->is<DependentMemberType>()) { type = type->getRootGenericParam(); if (proto->getProtocolSelfType()->isEqual(type)) return SelfReferenceKind::Other(); } return SelfReferenceKind::None(); } /// Find Self references in a generic signature's same-type requirements. static SelfReferenceKind findProtocolSelfReferences(const ProtocolDecl *protocol, GenericSignature *genericSig){ if (!genericSig) return SelfReferenceKind::None(); auto selfTy = protocol->getSelfInterfaceType(); for (const auto &req : genericSig->getRequirements()) { if (req.getKind() != RequirementKind::SameType) continue; if (req.getFirstType()->isEqual(selfTy) || req.getSecondType()->isEqual(selfTy)) return SelfReferenceKind::Requirement(); } return SelfReferenceKind::None(); } /// Find Self references within the given requirement. SelfReferenceKind ProtocolDecl::findProtocolSelfReferences(const ValueDecl *value, bool allowCovariantParameters, bool skipAssocTypes) const { // Types never refer to 'Self'. if (isa<TypeDecl>(value)) return SelfReferenceKind::None(); auto type = value->getInterfaceType(); // FIXME: Deal with broken recursion. if (!type) return SelfReferenceKind::None(); // Skip invalid declarations. if (type->hasError()) return SelfReferenceKind::None(); if (auto func = dyn_cast<AbstractFunctionDecl>(value)) { // Skip the 'self' parameter. type = type->castTo<AnyFunctionType>()->getResult(); // Methods of non-final classes can only contain a covariant 'Self' // as a function result type. if (!allowCovariantParameters) { auto inputKind = SelfReferenceKind::None(); for (auto &elt : type->castTo<AnyFunctionType>()->getParams()) { inputKind |= ::findProtocolSelfReferences(this, elt.getType(), skipAssocTypes); } if (inputKind.parameter) return SelfReferenceKind::Other(); } // Check the requirements of a generic function. if (func->isGeneric()) { if (auto result = ::findProtocolSelfReferences(this, func->getGenericSignature())) return result; } return ::findProtocolSelfReferences(this, type, skipAssocTypes); } else if (auto subscript = dyn_cast<SubscriptDecl>(value)) { // Check the requirements of a generic subscript. if (subscript->isGeneric()) { if (auto result = ::findProtocolSelfReferences(this, subscript->getGenericSignature())) return result; } return ::findProtocolSelfReferences(this, type, skipAssocTypes); } else { if (::findProtocolSelfReferences(this, type, skipAssocTypes)) { return SelfReferenceKind::Other(); } return SelfReferenceKind::None(); } } bool ProtocolDecl::isAvailableInExistential(const ValueDecl *decl) const { // If the member type uses 'Self' in non-covariant position, // we cannot use the existential type. auto selfKind = findProtocolSelfReferences(decl, /*allowCovariantParameters=*/true, /*skipAssocTypes=*/false); if (selfKind.parameter || selfKind.other) return false; return true; } bool ProtocolDecl::existentialTypeSupportedSlow(LazyResolver *resolver) { // Assume for now that the existential type is supported; this // prevents circularity issues. Bits.ProtocolDecl.ExistentialTypeSupportedValid = true; Bits.ProtocolDecl.ExistentialTypeSupported = true; // ObjC protocols can always be existential. if (isObjC()) return true; for (auto member : getMembers()) { // Check for associated types. if (isa<AssociatedTypeDecl>(member)) { // An existential type cannot be used if the protocol has an // associated type. Bits.ProtocolDecl.ExistentialTypeSupported = false; return false; } // For value members, look at their type signatures. if (auto valueMember = dyn_cast<ValueDecl>(member)) { // materializeForSet has a funny type signature. if (auto accessor = dyn_cast<AccessorDecl>(member)) { if (accessor->getAccessorKind() == AccessorKind::MaterializeForSet) continue; } if (resolver && !valueMember->hasInterfaceType()) resolver->resolveDeclSignature(valueMember); if (!isAvailableInExistential(valueMember)) { Bits.ProtocolDecl.ExistentialTypeSupported = false; return false; } } } // Check whether all of the inherited protocols can have existential // types themselves. for (auto proto : getInheritedProtocols()) { if (!proto->existentialTypeSupported(resolver)) { Bits.ProtocolDecl.ExistentialTypeSupported = false; return false; } } return true; } StringRef ProtocolDecl::getObjCRuntimeName( llvm::SmallVectorImpl<char> &buffer) const { // If there is an 'objc' attribute with a name, use that name. if (auto objc = getAttrs().getAttribute<ObjCAttr>()) { if (auto name = objc->getName()) return name->getString(buffer); } // Produce the mangled name for this protocol. return mangleObjCRuntimeName(this, buffer); } GenericParamList *ProtocolDecl::createGenericParams(DeclContext *dc) { auto *outerGenericParams = getParent()->getGenericParamsOfContext(); // The generic parameter 'Self'. auto &ctx = getASTContext(); auto selfId = ctx.Id_Self; auto selfDecl = new (ctx) GenericTypeParamDecl( dc, selfId, SourceLoc(), GenericTypeParamDecl::InvalidDepth, /*index=*/0); auto protoType = getDeclaredType(); TypeLoc selfInherited[1] = { TypeLoc::withoutLoc(protoType) }; selfDecl->setInherited(ctx.AllocateCopy(selfInherited)); selfDecl->setImplicit(); // The generic parameter list itself. auto result = GenericParamList::create(ctx, SourceLoc(), selfDecl, SourceLoc()); result->setOuterParameters(outerGenericParams); return result; } void ProtocolDecl::createGenericParamsIfMissing() { if (!getGenericParams()) setGenericParams(createGenericParams(this)); } void ProtocolDecl::computeRequirementSignature() { assert(!RequirementSignature && "already computed requirement signature"); // Compute and record the signature. auto requirementSig = GenericSignatureBuilder::computeRequirementSignature(this); RequirementSignature = requirementSig->getRequirements().data(); assert(RequirementSignature != nullptr); Bits.ProtocolDecl.NumRequirementsInSignature = requirementSig->getRequirements().size(); } void ProtocolDecl::setRequirementSignature(ArrayRef<Requirement> requirements) { assert(!RequirementSignature && "already computed requirement signature"); if (requirements.empty()) { RequirementSignature = reinterpret_cast<Requirement *>(this + 1); Bits.ProtocolDecl.NumRequirementsInSignature = 0; } else { RequirementSignature = getASTContext().AllocateCopy(requirements).data(); Bits.ProtocolDecl.NumRequirementsInSignature = requirements.size(); } } /// Returns the default witness for a requirement, or nullptr if there is /// no default. Witness ProtocolDecl::getDefaultWitness(ValueDecl *requirement) const { loadAllMembers(); auto found = DefaultWitnesses.find(requirement); if (found == DefaultWitnesses.end()) return Witness(); return found->second; } /// Record the default witness for a requirement. void ProtocolDecl::setDefaultWitness(ValueDecl *requirement, Witness witness) { assert(witness); // The first type we insert a default witness, register a destructor for // this type. if (DefaultWitnesses.empty()) getASTContext().addDestructorCleanup(DefaultWitnesses); auto pair = DefaultWitnesses.insert(std::make_pair(requirement, witness)); assert(pair.second && "Already have a default witness!"); (void) pair; } #ifndef NDEBUG static bool isAccessor(AccessorDecl *accessor, AccessorKind kind, AbstractStorageDecl *storage) { // TODO: this should check that the accessor belongs to this storage, but // the Clang importer currently likes to violate that condition. return (accessor && accessor->getAccessorKind() == kind); } #endif void AbstractStorageDecl::configureAccessor(AccessorDecl *accessor) { assert(isAccessor(accessor, accessor->getAccessorKind(), this)); switch (accessor->getAccessorKind()) { case AccessorKind::Get: case AccessorKind::Address: case AccessorKind::Read: // Nothing to do. return; case AccessorKind::Set: case AccessorKind::MaterializeForSet: case AccessorKind::WillSet: case AccessorKind::DidSet: case AccessorKind::MutableAddress: case AccessorKind::Modify: // Propagate the setter access. if (auto setterAccess = Accessors.getInt()) { assert(!accessor->hasAccess() || accessor->getFormalAccess() == setterAccess.getValue()); accessor->overwriteAccess(setterAccess.getValue()); } return; } llvm_unreachable("bad accessor kind"); } void AbstractStorageDecl::overwriteImplInfo(StorageImplInfo implInfo) { setFieldsFromImplInfo(implInfo); Accessors.getPointer()->overwriteImplInfo(implInfo); } void AbstractStorageDecl::setAccessors(StorageImplInfo implInfo, SourceLoc lbraceLoc, ArrayRef<AccessorDecl *> accessors, SourceLoc rbraceLoc) { setFieldsFromImplInfo(implInfo); // This method is called after we've already recorded an accessors clause // only on recovery paths and only when that clause was empty. auto record = Accessors.getPointer(); if (record) { assert(record->getAllAccessors().empty()); for (auto accessor : accessors) { (void) record->addOpaqueAccessor(accessor); } } else { record = AccessorRecord::create(getASTContext(), SourceRange(lbraceLoc, rbraceLoc), implInfo, accessors); Accessors.setPointer(record); } for (auto accessor : accessors) configureAccessor(accessor); } // Compute the number of opaque accessors. const size_t NumOpaqueAccessors = 0 #define ACCESSOR(ID) #define OPAQUE_ACCESSOR(ID, KEYWORD) \ + 1 #include "swift/AST/AccessorKinds.def" ; AbstractStorageDecl::AccessorRecord * AbstractStorageDecl::AccessorRecord::create(ASTContext &ctx, SourceRange braces, StorageImplInfo storageInfo, ArrayRef<AccessorDecl*> accessors) { // Silently cap the number of accessors we store at a number that should // be easily sufficient for all the valid cases, including space for adding // implicit opaque accessors later. // // We should have already emitted a diagnostic in the parser if we have // this many accessors, because most of them will necessarily be redundant. if (accessors.size() + NumOpaqueAccessors > MaxNumAccessors) { accessors = accessors.slice(0, MaxNumAccessors - NumOpaqueAccessors); } // Make sure that we have enough space to add implicit opaque accessors later. size_t numMissingOpaque = NumOpaqueAccessors; { #define ACCESSOR(ID) #define OPAQUE_ACCESSOR(ID, KEYWORD) \ bool has##ID = false; #include "swift/AST/AccessorKinds.def" for (auto accessor : accessors) { switch (accessor->getAccessorKind()) { #define ACCESSOR(ID) \ case AccessorKind::ID: \ continue; #define OPAQUE_ACCESSOR(ID, KEYWORD) \ case AccessorKind::ID: \ if (!has##ID) { \ has##ID = true; \ numMissingOpaque--; \ } \ continue; #include "swift/AST/AccessorKinds.def" } llvm_unreachable("bad accessor kind"); } } auto accessorsCapacity = AccessorIndex(accessors.size() + numMissingOpaque); void *mem = ctx.Allocate(totalSizeToAlloc<AccessorDecl*>(accessorsCapacity), alignof(AccessorRecord)); return new (mem) AccessorRecord(braces, storageInfo, accessors, accessorsCapacity); } AbstractStorageDecl::AccessorRecord::AccessorRecord(SourceRange braces, StorageImplInfo implInfo, ArrayRef<AccessorDecl *> accessors, AccessorIndex accessorsCapacity) : Braces(braces), ImplInfo(implInfo), NumAccessors(accessors.size()), AccessorsCapacity(accessorsCapacity), AccessorIndices{} { // Copy the complete accessors list into place. memcpy(getAccessorsBuffer().data(), accessors.data(), accessors.size() * sizeof(AccessorDecl*)); // Register all the accessors. for (auto index : indices(accessors)) { (void) registerAccessor(accessors[index], index); } } void AbstractStorageDecl::AccessorRecord::addOpaqueAccessor(AccessorDecl *decl){ assert(decl); // Add the accessor to the array. assert(NumAccessors < AccessorsCapacity); AccessorIndex index = NumAccessors++; getAccessorsBuffer()[index] = decl; // Register it. bool isUnique = registerAccessor(decl, index); assert(isUnique && "adding opaque accessor that's already present"); (void) isUnique; } /// Register that we have an accessor of the given kind. bool AbstractStorageDecl::AccessorRecord::registerAccessor(AccessorDecl *decl, AccessorIndex index){ // Remember that we have at least one accessor of this kind. auto &indexSlot = AccessorIndices[unsigned(decl->getAccessorKind())]; if (indexSlot) { return false; } else { indexSlot = index + 1; assert(getAccessor(decl->getAccessorKind()) == decl); return true; } } AccessLevel AbstractStorageDecl::getSetterFormalAccess() const { ASTContext &ctx = getASTContext(); return ctx.evaluator( SetterAccessLevelRequest{const_cast<AbstractStorageDecl *>(this)}); } void AbstractStorageDecl::setComputedSetter(AccessorDecl *setter) { assert(getImplInfo().getReadImpl() == ReadImplKind::Get); assert(!getImplInfo().supportsMutation()); assert(getGetter() && "sanity check: missing getter"); assert(!getSetter() && "already has a setter"); assert(hasClangNode() && "should only be used for ObjC properties"); assert(isAccessor(setter, AccessorKind::Set, this)); assert(setter && "should not be called for readonly properties"); overwriteImplInfo(StorageImplInfo::getMutableComputed()); Accessors.getPointer()->addOpaqueAccessor(setter); configureAccessor(setter); } void AbstractStorageDecl::setSynthesizedGetter(AccessorDecl *accessor) { assert(!getGetter() && "declaration doesn't already have getter!"); assert(isAccessor(accessor, AccessorKind::Get, this)); auto accessors = Accessors.getPointer(); if (!accessors) { accessors = AccessorRecord::create(getASTContext(), SourceRange(), getImplInfo(), {}); Accessors.setPointer(accessors); } accessors->addOpaqueAccessor(accessor); configureAccessor(accessor); } void AbstractStorageDecl::setSynthesizedSetter(AccessorDecl *accessor) { assert(getGetter() && "declaration doesn't already have getter!"); assert(supportsMutation() && "adding setter to immutable storage"); assert(isAccessor(accessor, AccessorKind::Set, this)); Accessors.getPointer()->addOpaqueAccessor(accessor); configureAccessor(accessor); } void AbstractStorageDecl::setSynthesizedMaterializeForSet(AccessorDecl *accessor) { assert(getGetter() && "declaration doesn't already have getter!"); assert(getSetter() && "declaration doesn't already have setter!"); assert(supportsMutation() && "adding materializeForSet to immutable storage"); assert(!getMaterializeForSetFunc() && "already has a materializeForSet"); assert(isAccessor(accessor, AccessorKind::MaterializeForSet, this)); Accessors.getPointer()->addOpaqueAccessor(accessor); configureAccessor(accessor); } void AbstractStorageDecl::addBehavior(TypeRepr *Type, Expr *Param) { assert(BehaviorInfo.getPointer() == nullptr && "already set behavior!"); auto mem = getASTContext().Allocate(sizeof(BehaviorRecord), alignof(BehaviorRecord)); auto behavior = new (mem) BehaviorRecord{Type, Param}; BehaviorInfo.setPointer(behavior); } static Optional<ObjCSelector> getNameFromObjcAttribute(const ObjCAttr *attr, DeclName preferredName) { if (!attr) return None; if (auto name = attr->getName()) { if (attr->isNameImplicit()) { // preferredName > implicit name, because implicit name is just cached // actual name. if (!preferredName) return *name; } else { // explicit name > preferred name. return *name; } } return None; } ObjCSelector AbstractStorageDecl::getObjCGetterSelector(Identifier preferredName) const { // If the getter has an @objc attribute with a name, use that. if (auto getter = getGetter()) { if (auto name = getNameFromObjcAttribute(getter->getAttrs(). getAttribute<ObjCAttr>(), preferredName)) return *name; } // Subscripts use a specific selector. auto &ctx = getASTContext(); if (auto *SD = dyn_cast<SubscriptDecl>(this)) { switch (SD->getObjCSubscriptKind()) { case ObjCSubscriptKind::None: llvm_unreachable("Not an Objective-C subscript"); case ObjCSubscriptKind::Indexed: return ObjCSelector(ctx, 1, ctx.Id_objectAtIndexedSubscript); case ObjCSubscriptKind::Keyed: return ObjCSelector(ctx, 1, ctx.Id_objectForKeyedSubscript); } } // The getter selector is the property name itself. auto var = cast<VarDecl>(this); auto name = var->getObjCPropertyName(); // Use preferred name is specified. if (!preferredName.empty()) name = preferredName; return VarDecl::getDefaultObjCGetterSelector(ctx, name); } ObjCSelector AbstractStorageDecl::getObjCSetterSelector(Identifier preferredName) const { // If the setter has an @objc attribute with a name, use that. auto setter = getSetter(); auto objcAttr = setter ? setter->getAttrs().getAttribute<ObjCAttr>() : nullptr; if (auto name = getNameFromObjcAttribute(objcAttr, DeclName(preferredName))) { return *name; } // Subscripts use a specific selector. auto &ctx = getASTContext(); if (auto *SD = dyn_cast<SubscriptDecl>(this)) { switch (SD->getObjCSubscriptKind()) { case ObjCSubscriptKind::None: llvm_unreachable("Not an Objective-C subscript"); case ObjCSubscriptKind::Indexed: return ObjCSelector(ctx, 2, { ctx.Id_setObject, ctx.Id_atIndexedSubscript }); case ObjCSubscriptKind::Keyed: return ObjCSelector(ctx, 2, { ctx.Id_setObject, ctx.Id_forKeyedSubscript }); } } // The setter selector for, e.g., 'fooBar' is 'setFooBar:', with the // property name capitalized and preceded by 'set'. auto var = cast<VarDecl>(this); Identifier Name = var->getObjCPropertyName(); if (!preferredName.empty()) Name = preferredName; auto result = VarDecl::getDefaultObjCSetterSelector(ctx, Name); // Cache the result, so we don't perform string manipulation again. if (objcAttr && preferredName.empty()) const_cast<ObjCAttr *>(objcAttr)->setName(result, /*implicit=*/true); return result; } SourceLoc AbstractStorageDecl::getOverrideLoc() const { if (auto *Override = getAttrs().getAttribute<OverrideAttr>()) return Override->getLocation(); return SourceLoc(); } Type AbstractStorageDecl::getValueInterfaceType() const { if (auto var = dyn_cast<VarDecl>(this)) return var->getInterfaceType()->getReferenceStorageReferent(); return cast<SubscriptDecl>(this)->getElementInterfaceType(); } Type VarDecl::getType() const { if (!typeInContext) { const_cast<VarDecl *>(this)->typeInContext = getDeclContext()->mapTypeIntoContext( getInterfaceType()); } return typeInContext; } void VarDecl::setType(Type t) { assert(t.isNull() || !t->is<InOutType>()); typeInContext = t; if (t && t->hasError()) setInvalid(); } void VarDecl::markInvalid() { auto &Ctx = getASTContext(); setType(ErrorType::get(Ctx)); setInterfaceType(ErrorType::get(Ctx)); setInvalid(); } /// \brief Returns whether the var is settable in the specified context: this /// is either because it is a stored var, because it has a custom setter, or /// is a let member in an initializer. bool VarDecl::isSettable(const DeclContext *UseDC, const DeclRefExpr *base) const { // If this is a 'var' decl, then we're settable if we have storage or a // setter. if (!isImmutable()) return supportsMutation(); // If the decl has a value bound to it but has no PBD, then it is // initialized. if (hasNonPatternBindingInit()) return false; // 'let' parameters are never settable. if (isa<ParamDecl>(this)) return false; // Properties in structs/classes are only ever mutable in their designated // initializer(s). if (isInstanceMember()) { auto *CD = dyn_cast_or_null<ConstructorDecl>(UseDC); if (!CD) return false; auto *CDC = CD->getDeclContext(); // 'let' properties are not valid inside protocols. if (CDC->getAsProtocolExtensionContext()) return false; // If this init is defined inside of the same type (or in an extension // thereof) as the let property, then it is mutable. if (!CDC->isTypeContext() || CDC->getAsNominalTypeOrNominalTypeExtensionContext() != getDeclContext()->getAsNominalTypeOrNominalTypeExtensionContext()) return false; if (base && CD->getImplicitSelfDecl() != base->getDecl()) return false; // If this is a convenience initializer (i.e. one that calls // self.init), then let properties are never mutable in it. They are // only mutable in designated initializers. if (CD->getDelegatingOrChainedInitKind(nullptr) == ConstructorDecl::BodyInitKind::Delegating) return false; return true; } // If the decl has an explicitly written initializer with a pattern binding, // then it isn't settable. if (getParentInitializer() != nullptr) return false; // Normal lets (e.g. globals) are only mutable in the context of the // declaration. To handle top-level code properly, we look through // the TopLevelCode decl on the use (if present) since the vardecl may be // one level up. if (getDeclContext() == UseDC) return true; if (UseDC && isa<TopLevelCodeDecl>(UseDC) && getDeclContext() == UseDC->getParent()) return true; return false; } bool SubscriptDecl::isSettable() const { return supportsMutation(); } SourceRange VarDecl::getSourceRange() const { if (auto Param = dyn_cast<ParamDecl>(this)) return Param->getSourceRange(); return getNameLoc(); } SourceRange VarDecl::getTypeSourceRangeForDiagnostics() const { // For a parameter, map back to its parameter to get the TypeLoc. if (auto *PD = dyn_cast<ParamDecl>(this)) { if (auto typeRepr = PD->getTypeLoc().getTypeRepr()) return typeRepr->getSourceRange(); } Pattern *Pat = getParentPattern(); if (!Pat || Pat->isImplicit()) return SourceRange(); if (auto *VP = dyn_cast<VarPattern>(Pat)) Pat = VP->getSubPattern(); if (auto *TP = dyn_cast<TypedPattern>(Pat)) if (auto typeRepr = TP->getTypeLoc().getTypeRepr()) return typeRepr->getSourceRange(); return SourceRange(); } static bool isVarInPattern(const VarDecl *VD, Pattern *P) { bool foundIt = false; P->forEachVariable([&](VarDecl *FoundFD) { foundIt |= FoundFD == VD; }); return foundIt; } /// Return the Pattern involved in initializing this VarDecl. Recall that the /// Pattern may be involved in initializing more than just this one vardecl /// though. For example, if this is a VarDecl for "x", the pattern may be /// "(x, y)" and the initializer on the PatternBindingDecl may be "(1,2)" or /// "foo()". /// /// If this has no parent pattern binding decl or statement associated, it /// returns null. /// Pattern *VarDecl::getParentPattern() const { // If this has a PatternBindingDecl parent, use its pattern. if (auto *PBD = getParentPatternBinding()) return PBD->getPatternEntryForVarDecl(this).getPattern(); // If this is a statement parent, dig the pattern out of it. if (auto *stmt = getParentPatternStmt()) { if (auto *FES = dyn_cast<ForEachStmt>(stmt)) return FES->getPattern(); if (auto *CS = dyn_cast<CatchStmt>(stmt)) return CS->getErrorPattern(); if (auto *cs = dyn_cast<CaseStmt>(stmt)) { // In a case statement, search for the pattern that contains it. This is // a bit silly, because you can't have something like "case x, y:" anyway. for (auto items : cs->getCaseLabelItems()) { if (isVarInPattern(this, items.getPattern())) return items.getPattern(); } } else if (auto *LCS = dyn_cast<LabeledConditionalStmt>(stmt)) { for (auto &elt : LCS->getCond()) if (auto pat = elt.getPatternOrNull()) if (isVarInPattern(this, pat)) return pat; } //stmt->dump(); assert(0 && "Unknown parent pattern statement?"); } return nullptr; } bool VarDecl::isSelfParameter() const { if (isa<ParamDecl>(this)) { if (auto *AFD = dyn_cast<AbstractFunctionDecl>(getDeclContext())) return AFD->getImplicitSelfDecl() == this; if (auto *PBI = dyn_cast<PatternBindingInitializer>(getDeclContext())) return PBI->getImplicitSelfDecl() == this; } return false; } void VarDecl::setSpecifier(Specifier specifier) { Bits.VarDecl.Specifier = static_cast<unsigned>(specifier); setSupportsMutationIfStillStored(!isImmutableSpecifier(specifier)); } bool VarDecl::isAnonClosureParam() const { auto name = getName(); if (name.empty()) return false; auto nameStr = name.str(); if (nameStr.empty()) return false; return nameStr[0] == '$'; } StaticSpellingKind VarDecl::getCorrectStaticSpelling() const { if (!isStatic()) return StaticSpellingKind::None; if (auto *PBD = getParentPatternBinding()) { if (PBD->getStaticSpelling() != StaticSpellingKind::None) return PBD->getStaticSpelling(); } return getCorrectStaticSpellingForDecl(this); } Identifier VarDecl::getObjCPropertyName() const { if (auto attr = getAttrs().getAttribute<ObjCAttr>()) { if (auto name = attr->getName()) return name->getSelectorPieces()[0]; } return getName(); } ObjCSelector VarDecl::getDefaultObjCGetterSelector(ASTContext &ctx, Identifier propertyName) { return ObjCSelector(ctx, 0, propertyName); } ObjCSelector VarDecl::getDefaultObjCSetterSelector(ASTContext &ctx, Identifier propertyName) { llvm::SmallString<16> scratch; scratch += "set"; camel_case::appendSentenceCase(scratch, propertyName.str()); return ObjCSelector(ctx, 1, ctx.getIdentifier(scratch)); } /// If this is a simple 'let' constant, emit a note with a fixit indicating /// that it can be rewritten to a 'var'. This is used in situations where the /// compiler detects obvious attempts to mutate a constant. void VarDecl::emitLetToVarNoteIfSimple(DeclContext *UseDC) const { // If it isn't a 'let', don't touch it. if (!isLet()) return; // If this is the 'self' argument of a non-mutating method in a value type, // suggest adding 'mutating' to the method. if (isSelfParameter() && UseDC) { // If the problematic decl is 'self', then we might be trying to mutate // a property in a non-mutating method. auto FD = dyn_cast_or_null<FuncDecl>(UseDC->getInnermostMethodContext()); if (FD && !FD->isMutating() && !FD->isImplicit() && FD->isInstanceMember()&& !FD->getDeclContext()->getDeclaredInterfaceType() ->hasReferenceSemantics()) { // Do not suggest the fix it in implicit getters if (auto AD = dyn_cast<AccessorDecl>(FD)) { if (AD->isGetter() && !AD->getAccessorKeywordLoc().isValid()) return; } auto &d = getASTContext().Diags; d.diagnose(FD->getFuncLoc(), diag::change_to_mutating, isa<AccessorDecl>(FD)) .fixItInsert(FD->getFuncLoc(), "mutating "); return; } } // Besides self, don't suggest mutability for explicit function parameters. if (isa<ParamDecl>(this)) return; // Don't suggest any fixes for capture list elements. if (isCaptureList()) return; // If this is a normal variable definition, then we can change 'let' to 'var'. // We even are willing to suggest this for multi-variable binding, like // "let (a,b) = " // since the user has to choose to apply this anyway. if (auto *PBD = getParentPatternBinding()) { // Don't touch generated or invalid code. if (PBD->getLoc().isInvalid() || PBD->isImplicit()) return; auto &d = getASTContext().Diags; d.diagnose(PBD->getLoc(), diag::convert_let_to_var) .fixItReplace(PBD->getLoc(), "var"); return; } } ParamDecl::ParamDecl(Specifier specifier, SourceLoc specifierLoc, SourceLoc argumentNameLoc, Identifier argumentName, SourceLoc parameterNameLoc, Identifier parameterName, Type ty, DeclContext *dc) : VarDecl(DeclKind::Param, /*IsStatic*/false, specifier, /*IsCaptureList*/false, parameterNameLoc, parameterName, ty, dc), ArgumentName(argumentName), ArgumentNameLoc(argumentNameLoc), SpecifierLoc(specifierLoc) { assert(specifier != Specifier::Var && "'var' cannot appear on parameters; you meant 'inout'"); Bits.ParamDecl.IsTypeLocImplicit = false; Bits.ParamDecl.defaultArgumentKind = static_cast<unsigned>(DefaultArgumentKind::None); } /// Clone constructor, allocates a new ParamDecl identical to the first. /// Intentionally not defined as a copy constructor to avoid accidental copies. ParamDecl::ParamDecl(ParamDecl *PD, bool withTypes) : VarDecl(DeclKind::Param, /*IsStatic*/false, PD->getSpecifier(), /*IsCaptureList*/false, PD->getNameLoc(), PD->getName(), PD->hasType() && withTypes ? PD->getType() : Type(), PD->getDeclContext()), ArgumentName(PD->getArgumentName()), ArgumentNameLoc(PD->getArgumentNameLoc()), SpecifierLoc(PD->getSpecifierLoc()), DefaultValueAndIsVariadic(nullptr, PD->DefaultValueAndIsVariadic.getInt()) { Bits.ParamDecl.IsTypeLocImplicit = PD->Bits.ParamDecl.IsTypeLocImplicit; Bits.ParamDecl.defaultArgumentKind = PD->Bits.ParamDecl.defaultArgumentKind; typeLoc = PD->getTypeLoc().clone(PD->getASTContext()); if (!withTypes && typeLoc.getTypeRepr()) typeLoc.setType(Type()); if (withTypes && PD->hasInterfaceType()) setInterfaceType(PD->getInterfaceType()->getInOutObjectType()); // FIXME: We should clone the entire attribute list. if (PD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) getAttrs().add(new (PD->getASTContext()) ImplicitlyUnwrappedOptionalAttr(/* implicit= */ true)); } /// \brief Retrieve the type of 'self' for the given context. Type DeclContext::getSelfTypeInContext() const { assert(isTypeContext()); // For a protocol or extension thereof, the type is 'Self'. if (getAsProtocolOrProtocolExtensionContext()) return mapTypeIntoContext(getProtocolSelfType()); return getDeclaredTypeInContext(); } /// \brief Retrieve the interface type of 'self' for the given context. Type DeclContext::getSelfInterfaceType() const { assert(isTypeContext()); // For a protocol or extension thereof, the type is 'Self'. if (getAsProtocolOrProtocolExtensionContext()) return getProtocolSelfType(); return getDeclaredInterfaceType(); } /// Create an implicit 'self' decl for a method in the specified decl context. /// If 'static' is true, then this is self for a static method in the type. /// /// Note that this decl is created, but it is returned with an incorrect /// DeclContext that needs to be set correctly. This is automatically handled /// when a function is created with this as part of its argument list. /// For a generic context, this also gives the parameter an unbound generic /// type with the expectation that type-checking will fill in the context /// generic parameters. ParamDecl *ParamDecl::createUnboundSelf(SourceLoc loc, DeclContext *DC) { ASTContext &C = DC->getASTContext(); auto *selfDecl = new (C) ParamDecl(VarDecl::Specifier::Default, SourceLoc(), SourceLoc(), Identifier(), loc, C.Id_self, Type(), DC); selfDecl->setImplicit(); return selfDecl; } /// Create an implicit 'self' decl for a method in the specified decl context. /// If 'static' is true, then this is self for a static method in the type. /// /// Note that this decl is created, but it is returned with an incorrect /// DeclContext that needs to be set correctly. This is automatically handled /// when a function is created with this as part of its argument list. /// For a generic context, this also gives the parameter an unbound generic /// type with the expectation that type-checking will fill in the context /// generic parameters. ParamDecl *ParamDecl::createSelf(SourceLoc loc, DeclContext *DC, bool isStaticMethod, bool isInOut) { ASTContext &C = DC->getASTContext(); auto selfInterfaceType = DC->getSelfInterfaceType(); auto specifier = VarDecl::Specifier::Default; assert(selfInterfaceType); if (isStaticMethod) { selfInterfaceType = MetatypeType::get(selfInterfaceType); } if (isInOut) { specifier = VarDecl::Specifier::InOut; } auto *selfDecl = new (C) ParamDecl(specifier, SourceLoc(),SourceLoc(), Identifier(), loc, C.Id_self, Type(), DC); selfDecl->setImplicit(); selfDecl->setInterfaceType(selfInterfaceType); selfDecl->setValidationToChecked(); return selfDecl; } ParameterTypeFlags ParamDecl::getParameterFlags() const { return ParameterTypeFlags::fromParameterType(getType(), isVariadic(), getValueOwnership()); } /// Return the full source range of this parameter. SourceRange ParamDecl::getSourceRange() const { SourceLoc APINameLoc = getArgumentNameLoc(); SourceLoc nameLoc = getNameLoc(); SourceLoc startLoc; if (APINameLoc.isValid()) startLoc = APINameLoc; else if (nameLoc.isValid()) startLoc = nameLoc; else { startLoc = getTypeLoc().getSourceRange().Start; } if (startLoc.isInvalid()) return SourceRange(); // It would be nice to extend the front of the range to show where inout is, // but we don't have that location info. Extend the back of the range to the // location of the default argument, or the typeloc if they are valid. if (auto expr = getDefaultValue()) { auto endLoc = expr->getEndLoc(); if (endLoc.isValid()) return SourceRange(startLoc, endLoc); } // If the typeloc has a valid location, use it to end the range. if (auto typeRepr = getTypeLoc().getTypeRepr()) { auto endLoc = typeRepr->getEndLoc(); if (endLoc.isValid() && !isTypeLocImplicit()) return SourceRange(startLoc, endLoc); } // The name has a location we can use. if (nameLoc.isValid()) return SourceRange(startLoc, nameLoc); return startLoc; } Type ParamDecl::getVarargBaseTy(Type VarArgT) { TypeBase *T = VarArgT.getPointer(); if (auto *AT = dyn_cast<ArraySliceType>(T)) return AT->getBaseType(); if (auto *BGT = dyn_cast<BoundGenericType>(T)) { // It's the stdlib Array<T>. return BGT->getGenericArgs()[0]; } return T; } void ParamDecl::setDefaultValue(Expr *E) { if (!DefaultValueAndIsVariadic.getPointer()) { if (!E) return; DefaultValueAndIsVariadic.setPointer( getASTContext().Allocate<StoredDefaultArgument>()); } DefaultValueAndIsVariadic.getPointer()->DefaultArg = E; } void ParamDecl::setDefaultArgumentInitContext(Initializer *initContext) { assert(DefaultValueAndIsVariadic.getPointer()); DefaultValueAndIsVariadic.getPointer()->InitContext = initContext; } void DefaultArgumentInitializer::changeFunction( DeclContext *parent, ParameterList *paramList) { if (parent->isLocalContext()) { setParent(parent); } auto param = paramList->get(getIndex()); if (param->getDefaultValue()) param->setDefaultArgumentInitContext(this); } /// Determine whether the given Swift type is an integral type, i.e., /// a type that wraps a builtin integer. static bool isIntegralType(Type type) { // Consider structs in the standard library module that wrap a builtin // integer type to be integral types. if (auto structTy = type->getAs<StructType>()) { auto structDecl = structTy->getDecl(); const DeclContext *DC = structDecl->getDeclContext(); if (!DC->isModuleScopeContext() || !DC->getParentModule()->isStdlibModule()) return false; // Find the single ivar. VarDecl *singleVar = nullptr; for (auto member : structDecl->getStoredProperties()) { if (singleVar) return false; singleVar = member; } if (!singleVar) return false; // Check whether it has integer type. return singleVar->getInterfaceType()->is<BuiltinIntegerType>(); } return false; } void SubscriptDecl::setIndices(ParameterList *p) { Indices = p; if (Indices) Indices->setDeclContextOfParamDecls(this); } Type SubscriptDecl::getIndicesInterfaceType() const { auto indicesTy = getInterfaceType(); if (indicesTy->hasError()) return indicesTy; return indicesTy->castTo<AnyFunctionType>()->getInput(); } Type SubscriptDecl::getElementInterfaceType() const { auto elementTy = getInterfaceType(); if (elementTy->hasError()) return elementTy; return elementTy->castTo<AnyFunctionType>()->getResult(); } void SubscriptDecl::computeType() { auto &ctx = getASTContext(); auto elementTy = getElementTypeLoc().getType(); auto indicesTy = getIndices()->getInterfaceType(ctx); Type funcTy; if (auto *sig = getGenericSignature()) funcTy = GenericFunctionType::get(sig, indicesTy, elementTy, AnyFunctionType::ExtInfo()); else funcTy = FunctionType::get(indicesTy, elementTy); // Record the interface type. setInterfaceType(funcTy); } ObjCSubscriptKind SubscriptDecl::getObjCSubscriptKind() const { // If the index type is an integral type, we have an indexed // subscript. if (auto funcTy = getInterfaceType()->getAs<AnyFunctionType>()) { auto params = funcTy->getParams(); if (params.size() == 1) if (isIntegralType(params[0].getPlainType())) return ObjCSubscriptKind::Indexed; } // If the index type is an object type in Objective-C, we have a // keyed subscript. return ObjCSubscriptKind::Keyed; } SourceRange SubscriptDecl::getSourceRange() const { if (getBracesRange().isValid()) { return { getSubscriptLoc(), getBracesRange().End }; } else if (ElementTy.getSourceRange().End.isValid()) { return { getSubscriptLoc(), ElementTy.getSourceRange().End }; } else if (ArrowLoc.isValid()) { return { getSubscriptLoc(), ArrowLoc }; } else { return getSubscriptLoc(); } } SourceRange SubscriptDecl::getSignatureSourceRange() const { if (isImplicit()) return SourceRange(); if (auto Indices = getIndices()) { auto End = Indices->getEndLoc(); if (End.isValid()) { return SourceRange(getSubscriptLoc(), End); } } return getSubscriptLoc(); } DeclName AbstractFunctionDecl::getEffectiveFullName() const { if (getFullName()) return getFullName(); if (auto accessor = dyn_cast<AccessorDecl>(this)) { auto &ctx = getASTContext(); auto storage = accessor->getStorage(); auto subscript = dyn_cast<SubscriptDecl>(storage); switch (auto accessorKind = accessor->getAccessorKind()) { // These don't have any extra implicit parameters. case AccessorKind::Address: case AccessorKind::MutableAddress: case AccessorKind::Get: case AccessorKind::Read: case AccessorKind::Modify: return subscript ? subscript->getFullName() : DeclName(ctx, storage->getBaseName(), ArrayRef<Identifier>()); case AccessorKind::Set: case AccessorKind::MaterializeForSet: case AccessorKind::DidSet: case AccessorKind::WillSet: { SmallVector<Identifier, 4> argNames; // The implicit value/buffer parameter. argNames.push_back(Identifier()); // The callback storage parameter on materializeForSet. if (accessorKind == AccessorKind::MaterializeForSet) argNames.push_back(Identifier()); // The subscript index parameters. if (subscript) { argNames.append(subscript->getFullName().getArgumentNames().begin(), subscript->getFullName().getArgumentNames().end()); } return DeclName(ctx, storage->getBaseName(), argNames); } } llvm_unreachable("bad accessor kind"); } return DeclName(); } std::pair<DefaultArgumentKind, Type> swift::getDefaultArgumentInfo(ValueDecl *source, unsigned Index) { const ParameterList *paramList; if (auto *AFD = dyn_cast<AbstractFunctionDecl>(source)) { paramList = AFD->getParameters(); } else { paramList = cast<EnumElementDecl>(source)->getParameterList(); } auto param = paramList->get(Index); return { param->getDefaultArgumentKind(), param->getInterfaceType() }; } Type AbstractFunctionDecl::getMethodInterfaceType() const { assert(getDeclContext()->isTypeContext()); auto Ty = getInterfaceType(); if (Ty->hasError()) return ErrorType::get(getASTContext()); return Ty->castTo<AnyFunctionType>()->getResult(); } bool AbstractFunctionDecl::argumentNameIsAPIByDefault() const { // Initializers have argument labels. if (isa<ConstructorDecl>(this)) return true; if (auto func = dyn_cast<FuncDecl>(this)) { // Operators do not have argument labels. if (func->isOperator()) return false; // Other functions have argument labels for all arguments return true; } assert(isa<DestructorDecl>(this)); return false; } SourceRange AbstractFunctionDecl::getBodySourceRange() const { switch (getBodyKind()) { case BodyKind::None: case BodyKind::MemberwiseInitializer: return SourceRange(); case BodyKind::Parsed: case BodyKind::Synthesize: case BodyKind::TypeChecked: if (auto body = getBody()) return body->getSourceRange(); return SourceRange(); case BodyKind::Skipped: case BodyKind::Unparsed: return BodyRange; } llvm_unreachable("bad BodyKind"); } SourceRange AbstractFunctionDecl::getSignatureSourceRange() const { if (isImplicit()) return SourceRange(); auto paramList = getParameters(); auto endLoc = paramList->getSourceRange().End; if (endLoc.isValid()) return SourceRange(getNameLoc(), endLoc); return getNameLoc(); } ObjCSelector AbstractFunctionDecl::getObjCSelector(DeclName preferredName) const { // FIXME: Forces computation of the Objective-C selector. if (getASTContext().getLazyResolver()) (void)isObjC(); // If there is an @objc attribute with a name, use that name. auto *objc = getAttrs().getAttribute<ObjCAttr>(); if (auto name = getNameFromObjcAttribute(objc, preferredName)) { return *name; } auto &ctx = getASTContext(); StringRef baseNameStr; if (isa<DestructorDecl>(this)) { // Deinitializers are always called "dealloc". return ObjCSelector(ctx, 0, ctx.Id_dealloc); } else if (auto func = dyn_cast<FuncDecl>(this)) { // Otherwise cast this to be able to access getName() baseNameStr = func->getName().str(); } else if (auto ctor = dyn_cast<ConstructorDecl>(this)) { baseNameStr = "init"; } else { llvm_unreachable("Unknown subclass of AbstractFunctionDecl"); } auto argNames = getFullName().getArgumentNames(); // Use the preferred name if specified if (preferredName) { // Return invalid selector if argument count doesn't match. if (argNames.size() != preferredName.getArgumentNames().size()) { return ObjCSelector(); } baseNameStr = preferredName.getBaseName().userFacingName(); argNames = preferredName.getArgumentNames(); } auto baseName = ctx.getIdentifier(baseNameStr); if (auto accessor = dyn_cast<AccessorDecl>(this)) { // For a getter or setter, go through the variable or subscript decl. auto asd = accessor->getStorage(); if (accessor->isGetter()) return asd->getObjCGetterSelector(baseName); if (accessor->isSetter()) return asd->getObjCSetterSelector(baseName); } // If this is a zero-parameter initializer with a long selector // name, form that selector. auto ctor = dyn_cast<ConstructorDecl>(this); if (ctor && ctor->isObjCZeroParameterWithLongSelector()) { Identifier firstName = argNames[0]; llvm::SmallString<16> scratch; scratch += "init"; // If the first argument name doesn't start with a preposition, add "with". if (getPrepositionKind(camel_case::getFirstWord(firstName.str())) == PK_None) { camel_case::appendSentenceCase(scratch, "With"); } camel_case::appendSentenceCase(scratch, firstName.str()); return ObjCSelector(ctx, 0, ctx.getIdentifier(scratch)); } // The number of selector pieces we'll have. Optional<ForeignErrorConvention> errorConvention = getForeignErrorConvention(); unsigned numSelectorPieces = argNames.size() + (errorConvention.hasValue() ? 1 : 0); // If we have no arguments, it's a nullary selector. if (numSelectorPieces == 0) { return ObjCSelector(ctx, 0, baseName); } // If it's a unary selector with no name for the first argument, we're done. if (numSelectorPieces == 1 && argNames.size() == 1 && argNames[0].empty()) { return ObjCSelector(ctx, 1, baseName); } /// Collect the selector pieces. SmallVector<Identifier, 4> selectorPieces; selectorPieces.reserve(numSelectorPieces); bool didStringManipulation = false; unsigned argIndex = 0; for (unsigned piece = 0; piece != numSelectorPieces; ++piece) { if (piece > 0) { // If we have an error convention that inserts an error parameter // here, add "error". if (errorConvention && piece == errorConvention->getErrorParameterIndex()) { selectorPieces.push_back(ctx.Id_error); continue; } // Selector pieces beyond the first are simple. selectorPieces.push_back(argNames[argIndex++]); continue; } // For the first selector piece, attach either the first parameter // or "AndReturnError" to the base name, if appropriate. auto firstPiece = baseName; llvm::SmallString<32> scratch; scratch += firstPiece.str(); if (errorConvention && piece == errorConvention->getErrorParameterIndex()) { // The error is first; append "AndReturnError". camel_case::appendSentenceCase(scratch, "AndReturnError"); firstPiece = ctx.getIdentifier(scratch); didStringManipulation = true; } else if (!argNames[argIndex].empty()) { // If the first argument name doesn't start with a preposition, and the // method name doesn't end with a preposition, add "with". auto firstName = argNames[argIndex++]; if (getPrepositionKind(camel_case::getFirstWord(firstName.str())) == PK_None && getPrepositionKind(camel_case::getLastWord(firstPiece.str())) == PK_None) { camel_case::appendSentenceCase(scratch, "With"); } camel_case::appendSentenceCase(scratch, firstName.str()); firstPiece = ctx.getIdentifier(scratch); didStringManipulation = true; } else { ++argIndex; } selectorPieces.push_back(firstPiece); } assert(argIndex == argNames.size()); // Form the result. auto result = ObjCSelector(ctx, selectorPieces.size(), selectorPieces); // If we did any string manipulation, cache the result. We don't want to // do that again. if (didStringManipulation && objc && !preferredName) const_cast<ObjCAttr *>(objc)->setName(result, /*implicit=*/true); return result; } bool AbstractFunctionDecl::isObjCInstanceMethod() const { return isInstanceMember() || isa<ConstructorDecl>(this); } static bool requiresNewVTableEntry(const AbstractFunctionDecl *decl) { assert(isa<FuncDecl>(decl) || isa<ConstructorDecl>(decl)); // Final members are always be called directly. // Dynamic methods are always accessed by objc_msgSend(). if (decl->isFinal() || decl->isDynamic() || decl->hasClangNode()) return false; if (auto *accessor = dyn_cast<AccessorDecl>(decl)) { switch (accessor->getAccessorKind()) { case AccessorKind::Get: case AccessorKind::Set: break; case AccessorKind::Address: case AccessorKind::MutableAddress: case AccessorKind::Read: case AccessorKind::Modify: return false; case AccessorKind::MaterializeForSet: // Special case -- materializeForSet on dynamic storage is not // itself dynamic, but should be treated as such for the // purpose of constructing a vtable. // FIXME: It should probably just be 'final'. if (accessor->getStorage()->isDynamic()) return false; break; case AccessorKind::WillSet: case AccessorKind::DidSet: return false; } } auto base = decl->getOverriddenDecl(); if (!base || base->hasClangNode() || base->isDynamic()) return true; // If the method overrides something, we only need a new entry if the // override has a more general AST type. However an abstraction // change is OK; we don't want to add a whole new vtable entry just // because an @in parameter because @owned, or whatever. auto baseInterfaceTy = base->getInterfaceType(); auto derivedInterfaceTy = decl->getInterfaceType(); auto selfInterfaceTy = decl->getDeclContext()->getDeclaredInterfaceType(); auto overrideInterfaceTy = selfInterfaceTy->adjustSuperclassMemberDeclType( base, decl, baseInterfaceTy); return !derivedInterfaceTy->matches(overrideInterfaceTy, TypeMatchFlags::AllowABICompatible); } void AbstractFunctionDecl::computeNeedsNewVTableEntry() { setNeedsNewVTableEntry(requiresNewVTableEntry(this)); } void AbstractFunctionDecl::setParameters(ParamDecl *SelfDecl, ParameterList *BodyParams) { #ifndef NDEBUG auto Name = getFullName(); if (!isa<DestructorDecl>(this)) assert((!Name || !Name.isSimpleName()) && "Must have a compound name"); assert(!Name || (Name.getArgumentNames().size() == BodyParams->size())); #endif assert(Bits.AbstractFunctionDecl.HasImplicitSelfDecl == (SelfDecl != nullptr)); if (SelfDecl) { *getImplicitSelfDeclStorage() = SelfDecl; SelfDecl->setDeclContext(this); } Params = BodyParams; BodyParams->setDeclContextOfParamDecls(this); } void AbstractFunctionDecl::computeType(AnyFunctionType::ExtInfo info) { auto &ctx = getASTContext(); auto *sig = getGenericSignature(); bool hasSelf = hasImplicitSelfDecl(); // Result Type resultTy; if (auto fn = dyn_cast<FuncDecl>(this)) { resultTy = fn->getBodyResultTypeLoc().getType(); if (!resultTy) resultTy = TupleType::getEmpty(ctx); } else if (auto ctor = dyn_cast<ConstructorDecl>(this)) { auto *dc = ctor->getDeclContext(); if (hasSelf) { if (!dc->isTypeContext()) resultTy = ErrorType::get(ctx); else resultTy = dc->getSelfInterfaceType(); } // Adjust result type for failability. if (ctor->getFailability() != OTK_None) resultTy = OptionalType::get(resultTy); } else { assert(isa<DestructorDecl>(this)); resultTy = TupleType::getEmpty(ctx); } // (Args...) -> Result Type funcTy; { SmallVector<AnyFunctionType::Param, 4> argTy; AnyFunctionType::decomposeInput( getParameters()->getInterfaceType(ctx), argTy); // 'throws' only applies to the innermost function. info = info.withThrows(hasThrows()); // Defer bodies must not escape. if (auto fd = dyn_cast<FuncDecl>(this)) info = info.withNoEscape(fd->isDeferBody()); if (sig && !hasSelf) { funcTy = GenericFunctionType::get(sig, argTy, resultTy, info); } else { funcTy = FunctionType::get(argTy, resultTy, info); } } Type initFuncTy; // (Self) -> (Args...) -> Result if (hasSelf) { SmallVector<AnyFunctionType::Param, 1> argTy; SmallVector<AnyFunctionType::Param, 1> initArgTy; // Substitute in our own 'self' parameter. argTy.push_back(computeSelfParam(this)); if (isa<ConstructorDecl>(this)) initArgTy.push_back(computeSelfParam(this, /*isInitializingCtor=*/true)); AnyFunctionType::ExtInfo info; if (sig) { if (isa<ConstructorDecl>(this)) initFuncTy = GenericFunctionType::get(sig, initArgTy, funcTy, info); funcTy = GenericFunctionType::get(sig, argTy, funcTy, info); } else { if (isa<ConstructorDecl>(this)) initFuncTy = FunctionType::get(initArgTy, funcTy, info); funcTy = FunctionType::get(argTy, funcTy, info); } } // Record the interface type. setInterfaceType(funcTy); if (auto *ctor = dyn_cast<ConstructorDecl>(this)) ctor->setInitializerInterfaceType(initFuncTy); } FuncDecl *FuncDecl::createImpl(ASTContext &Context, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Throws, SourceLoc ThrowsLoc, GenericParamList *GenericParams, bool HasImplicitSelfDecl, DeclContext *Parent, ClangNode ClangN) { size_t Size = sizeof(FuncDecl) + (HasImplicitSelfDecl ? sizeof(ParamDecl *) : 0); void *DeclPtr = allocateMemoryForDecl<FuncDecl>(Context, Size, !ClangN.isNull()); auto D = ::new (DeclPtr) FuncDecl(DeclKind::Func, StaticLoc, StaticSpelling, FuncLoc, Name, NameLoc, Throws, ThrowsLoc, HasImplicitSelfDecl, GenericParams, Parent); if (ClangN) D->setClangNode(ClangN); return D; } FuncDecl *FuncDecl::createDeserialized(ASTContext &Context, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Throws, SourceLoc ThrowsLoc, GenericParamList *GenericParams, bool HasImplicitSelfDecl, DeclContext *Parent) { return createImpl(Context, StaticLoc, StaticSpelling, FuncLoc, Name, NameLoc, Throws, ThrowsLoc, GenericParams, HasImplicitSelfDecl, Parent, ClangNode()); } FuncDecl *FuncDecl::create(ASTContext &Context, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Throws, SourceLoc ThrowsLoc, GenericParamList *GenericParams, ParamDecl *SelfDecl, ParameterList *BodyParams, TypeLoc FnRetType, DeclContext *Parent, ClangNode ClangN) { assert((SelfDecl != nullptr) == Parent->isTypeContext()); auto *FD = FuncDecl::createImpl( Context, StaticLoc, StaticSpelling, FuncLoc, Name, NameLoc, Throws, ThrowsLoc, GenericParams, SelfDecl != nullptr, Parent, ClangN); FD->setParameters(SelfDecl, BodyParams); FD->getBodyResultTypeLoc() = FnRetType; return FD; } AccessorDecl *AccessorDecl::createImpl(ASTContext &ctx, SourceLoc declLoc, SourceLoc accessorKeywordLoc, AccessorKind accessorKind, AddressorKind addressorKind, AbstractStorageDecl *storage, SourceLoc staticLoc, StaticSpellingKind staticSpelling, bool throws, SourceLoc throwsLoc, bool hasImplicitSelfDecl, GenericParamList *genericParams, DeclContext *parent, ClangNode clangNode) { size_t size = sizeof(AccessorDecl) + (hasImplicitSelfDecl ? sizeof(ParamDecl *) : 0); void *buffer = allocateMemoryForDecl<AccessorDecl>(ctx, size, !clangNode.isNull()); auto D = ::new (buffer) AccessorDecl(declLoc, accessorKeywordLoc, accessorKind, addressorKind, storage, staticLoc, staticSpelling, throws, throwsLoc, hasImplicitSelfDecl, genericParams, parent); if (clangNode) D->setClangNode(clangNode); return D; } AccessorDecl *AccessorDecl::createDeserialized(ASTContext &ctx, SourceLoc declLoc, SourceLoc accessorKeywordLoc, AccessorKind accessorKind, AddressorKind addressorKind, AbstractStorageDecl *storage, SourceLoc staticLoc, StaticSpellingKind staticSpelling, bool throws, SourceLoc throwsLoc, GenericParamList *genericParams, bool hasImplicitSelfDecl, DeclContext *parent) { return createImpl(ctx, declLoc, accessorKeywordLoc, accessorKind, addressorKind, storage, staticLoc, staticSpelling, throws, throwsLoc, hasImplicitSelfDecl, genericParams, parent, ClangNode()); } AccessorDecl *AccessorDecl::create(ASTContext &ctx, SourceLoc declLoc, SourceLoc accessorKeywordLoc, AccessorKind accessorKind, AddressorKind addressorKind, AbstractStorageDecl *storage, SourceLoc staticLoc, StaticSpellingKind staticSpelling, bool throws, SourceLoc throwsLoc, GenericParamList *genericParams, ParamDecl *selfDecl, ParameterList * bodyParams, TypeLoc fnRetType, DeclContext *parent, ClangNode clangNode) { auto *D = AccessorDecl::createImpl( ctx, declLoc, accessorKeywordLoc, accessorKind, addressorKind, storage, staticLoc, staticSpelling, throws, throwsLoc, selfDecl != nullptr, genericParams, parent, clangNode); D->setParameters(selfDecl, bodyParams); D->getBodyResultTypeLoc() = fnRetType; return D; } StaticSpellingKind FuncDecl::getCorrectStaticSpelling() const { assert(getDeclContext()->isTypeContext()); if (!isStatic()) return StaticSpellingKind::None; if (getStaticSpelling() != StaticSpellingKind::None) return getStaticSpelling(); return getCorrectStaticSpellingForDecl(this); } bool FuncDecl::isExplicitNonMutating() const { if (auto accessor = dyn_cast<AccessorDecl>(this)) { return !isMutating() && !accessor->isGetter() && isInstanceMember() && !getDeclContext()->getDeclaredInterfaceType()->hasReferenceSemantics(); } return false; } Type FuncDecl::getResultInterfaceType() const { if (!hasInterfaceType()) return nullptr; Type resultTy = getInterfaceType(); if (resultTy->is<ErrorType>()) return resultTy; if (hasImplicitSelfDecl()) resultTy = resultTy->castTo<AnyFunctionType>()->getResult(); return resultTy->castTo<AnyFunctionType>()->getResult(); } bool FuncDecl::isUnaryOperator() const { if (!isOperator()) return false; auto *params = getParameters(); return params->size() == 1 && !params->get(0)->isVariadic(); } bool FuncDecl::isBinaryOperator() const { if (!isOperator()) return false; auto *params = getParameters(); return params->size() == 2 && !params->get(0)->isVariadic() && !params->get(1)->isVariadic(); } ConstructorDecl::ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc, OptionalTypeKind Failability, SourceLoc FailabilityLoc, bool Throws, SourceLoc ThrowsLoc, ParamDecl *SelfDecl, ParameterList *BodyParams, GenericParamList *GenericParams, DeclContext *Parent) : AbstractFunctionDecl(DeclKind::Constructor, Parent, Name, ConstructorLoc, Throws, ThrowsLoc, /*HasImplicitSelfDecl=*/true, GenericParams), FailabilityLoc(FailabilityLoc) { if (BodyParams) setParameters(SelfDecl, BodyParams); Bits.ConstructorDecl.ComputedBodyInitKind = 0; Bits.ConstructorDecl.HasStubImplementation = 0; Bits.ConstructorDecl.InitKind = static_cast<unsigned>(CtorInitializerKind::Designated); Bits.ConstructorDecl.Failability = static_cast<unsigned>(Failability); assert(Name.getBaseName() == DeclBaseName::createConstructor()); } bool ConstructorDecl::isObjCZeroParameterWithLongSelector() const { // The initializer must have a single, non-empty argument name. if (getFullName().getArgumentNames().size() != 1 || getFullName().getArgumentNames()[0].empty()) return false; auto *params = getParameters(); if (params->size() != 1) return false; return params->get(0)->getInterfaceType()->isVoid(); } DestructorDecl::DestructorDecl(SourceLoc DestructorLoc, ParamDecl *selfDecl, DeclContext *Parent) : AbstractFunctionDecl(DeclKind::Destructor, Parent, DeclBaseName::createDestructor(), DestructorLoc, /*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*HasImplicitSelfDecl=*/true, /*GenericParams=*/nullptr) { if (selfDecl) { setParameters(selfDecl, ParameterList::createEmpty(Parent->getASTContext())); } } SourceRange FuncDecl::getSourceRange() const { SourceLoc StartLoc = getStartLoc(); if (StartLoc.isInvalid() || getBodyKind() == BodyKind::Synthesize) return SourceRange(); if (getBodyKind() == BodyKind::Unparsed || getBodyKind() == BodyKind::Skipped) return { StartLoc, BodyRange.End }; if (auto *B = getBody()) { if (!B->isImplicit()) return { StartLoc, B->getEndLoc() }; } if (isa<AccessorDecl>(this)) return StartLoc; auto TrailingWhereClauseSourceRange = getGenericTrailingWhereClauseSourceRange(); if (TrailingWhereClauseSourceRange.isValid()) return { StartLoc, TrailingWhereClauseSourceRange.End }; if (getBodyResultTypeLoc().hasLocation() && getBodyResultTypeLoc().getSourceRange().End.isValid()) return { StartLoc, getBodyResultTypeLoc().getSourceRange().End }; if (hasThrows()) return { StartLoc, getThrowsLoc() }; auto LastParamListEndLoc = getParameters()->getSourceRange().End; if (LastParamListEndLoc.isValid()) return { StartLoc, LastParamListEndLoc }; return StartLoc; } SourceRange EnumElementDecl::getSourceRange() const { if (RawValueExpr && !RawValueExpr->isImplicit()) return {getStartLoc(), RawValueExpr->getEndLoc()}; if (auto *PL = getParameterList()) return {getStartLoc(), PL->getSourceRange().End}; return {getStartLoc(), getNameLoc()}; } bool EnumElementDecl::computeType() { assert(!hasInterfaceType()); EnumDecl *ED = getParentEnum(); Type resultTy = ED->getDeclaredInterfaceType(); if (resultTy->hasError()) { setInterfaceType(resultTy); setInvalid(); return false; } Type selfTy = MetatypeType::get(resultTy); // The type of the enum element is either (T) -> T or (T) -> ArgType -> T. if (auto *PL = getParameterList()) { auto paramTy = PL->getInterfaceType(getASTContext()); resultTy = FunctionType::get(paramTy, resultTy); } if (auto *genericSig = ED->getGenericSignatureOfContext()) resultTy = GenericFunctionType::get(genericSig, selfTy, resultTy, AnyFunctionType::ExtInfo()); else resultTy = FunctionType::get(selfTy, resultTy); // Record the interface type. setInterfaceType(resultTy); return true; } Type EnumElementDecl::getArgumentInterfaceType() const { if (!hasAssociatedValues()) return nullptr; auto interfaceType = getInterfaceType(); if (interfaceType->hasError()) { return interfaceType; } auto funcTy = interfaceType->castTo<AnyFunctionType>(); funcTy = funcTy->getResult()->castTo<AnyFunctionType>(); return funcTy->getInput(); } EnumCaseDecl *EnumElementDecl::getParentCase() const { for (EnumCaseDecl *EC : getParentEnum()->getAllCases()) { ArrayRef<EnumElementDecl *> CaseElements = EC->getElements(); if (std::find(CaseElements.begin(), CaseElements.end(), this) != CaseElements.end()) { return EC; } } llvm_unreachable("enum element not in case of parent enum"); } SourceRange ConstructorDecl::getSourceRange() const { if (isImplicit()) return getConstructorLoc(); if (getBodyKind() == BodyKind::Unparsed || getBodyKind() == BodyKind::Skipped) return { getConstructorLoc(), BodyRange.End }; SourceLoc End; if (auto body = getBody()) End = body->getEndLoc(); if (End.isInvalid()) End = getGenericTrailingWhereClauseSourceRange().End; if (End.isInvalid()) End = getThrowsLoc(); if (End.isInvalid()) End = getSignatureSourceRange().End; return { getConstructorLoc(), End }; } Type ConstructorDecl::getArgumentInterfaceType() const { Type ArgTy = getInterfaceType(); ArgTy = ArgTy->castTo<AnyFunctionType>()->getResult(); ArgTy = ArgTy->castTo<AnyFunctionType>()->getInput(); return ArgTy; } Type ConstructorDecl::getResultInterfaceType() const { Type ArgTy = getInterfaceType(); ArgTy = ArgTy->castTo<AnyFunctionType>()->getResult(); ArgTy = ArgTy->castTo<AnyFunctionType>()->getResult(); return ArgTy; } Type ConstructorDecl::getInitializerInterfaceType() { return InitializerInterfaceType; } void ConstructorDecl::setInitializerInterfaceType(Type t) { InitializerInterfaceType = t; } ConstructorDecl::BodyInitKind ConstructorDecl::getDelegatingOrChainedInitKind(DiagnosticEngine *diags, ApplyExpr **init) const { assert(hasBody() && "Constructor does not have a definition"); if (init) *init = nullptr; // If we already computed the result, return it. if (Bits.ConstructorDecl.ComputedBodyInitKind) { return static_cast<BodyInitKind>( Bits.ConstructorDecl.ComputedBodyInitKind - 1); } struct FindReferenceToInitializer : ASTWalker { const ConstructorDecl *Decl; BodyInitKind Kind = BodyInitKind::None; ApplyExpr *InitExpr = nullptr; DiagnosticEngine *Diags; FindReferenceToInitializer(const ConstructorDecl *decl, DiagnosticEngine *diags) : Decl(decl), Diags(diags) { } bool walkToDeclPre(class Decl *D) override { // Don't walk into further nominal decls. return !isa<NominalTypeDecl>(D); } std::pair<bool, Expr*> walkToExprPre(Expr *E) override { // Don't walk into closures. if (isa<ClosureExpr>(E)) return { false, E }; // Look for calls of a constructor on self or super. auto apply = dyn_cast<ApplyExpr>(E); if (!apply) return { true, E }; auto Callee = apply->getSemanticFn(); Expr *arg; if (isa<OtherConstructorDeclRefExpr>(Callee)) { arg = apply->getArg(); } else if (auto *CRE = dyn_cast<ConstructorRefCallExpr>(Callee)) { arg = CRE->getArg(); } else if (auto *dotExpr = dyn_cast<UnresolvedDotExpr>(Callee)) { if (dotExpr->getName().getBaseName() != DeclBaseName::createConstructor()) return { true, E }; arg = dotExpr->getBase(); } else { // Not a constructor call. return { true, E }; } // Look for a base of 'self' or 'super'. BodyInitKind myKind; if (arg->isSuperExpr()) myKind = BodyInitKind::Chained; else if (arg->isSelfExprOf(Decl, /*sameBase*/true)) myKind = BodyInitKind::Delegating; else { // We're constructing something else. return { true, E }; } if (Kind == BodyInitKind::None) { Kind = myKind; // If we're not emitting diagnostics, we're done. if (!Diags) return { false, nullptr }; InitExpr = apply; return { true, E }; } assert(Diags && "Failed to abort traversal early"); // If the kind changed, complain. if (Kind != myKind) { // The kind changed. Complain. Diags->diagnose(E->getLoc(), diag::init_delegates_and_chains); Diags->diagnose(InitExpr->getLoc(), diag::init_delegation_or_chain, Kind == BodyInitKind::Chained); } return { true, E }; } }; FindReferenceToInitializer finder(this, diags); getBody()->walk(finder); // get the kind out of the finder. auto Kind = finder.Kind; auto *NTD = getDeclContext()->getAsNominalTypeOrNominalTypeExtensionContext(); // Protocol extension and enum initializers are always delegating. if (Kind == BodyInitKind::None) { if (isa<ProtocolDecl>(NTD) || isa<EnumDecl>(NTD)) { Kind = BodyInitKind::Delegating; } } // Struct initializers that cannot see the layout of the struct type are // always delegating. This occurs if the struct type is not fixed layout, // and the constructor is either inlinable or defined in another module. if (Kind == BodyInitKind::None && isa<StructDecl>(NTD)) { // Note: This is specifically not using isFormallyResilient. We relax this // rule for structs in non-resilient modules so that they can have inlinable // constructors, as long as those constructors don't reference private // declarations. if (NTD->isResilient() && getResilienceExpansion() == ResilienceExpansion::Minimal) { Kind = BodyInitKind::Delegating; } else if (isa<ExtensionDecl>(getDeclContext())) { const ModuleDecl *containingModule = getParentModule(); // Prior to Swift 5, cross-module initializers were permitted to be // non-delegating. However, if the struct isn't fixed-layout, we have to // be delegating because, well, we don't know the layout. if (NTD->isResilient() || containingModule->getASTContext().isSwiftVersionAtLeast(5)) { if (containingModule != NTD->getParentModule()) Kind = BodyInitKind::Delegating; } } } // If we didn't find any delegating or chained initializers, check whether // the initializer was explicitly marked 'convenience'. if (Kind == BodyInitKind::None && getAttrs().hasAttribute<ConvenienceAttr>()) Kind = BodyInitKind::Delegating; // If we still don't know, check whether we have a class with a superclass: it // gets an implicit chained initializer. if (Kind == BodyInitKind::None) { if (auto classDecl = getDeclContext()->getAsClassOrClassExtensionContext()) { if (classDecl->hasSuperclass()) Kind = BodyInitKind::ImplicitChained; } } // Cache the result if it is trustworthy. if (diags) { auto *mutableThis = const_cast<ConstructorDecl *>(this); mutableThis->Bits.ConstructorDecl.ComputedBodyInitKind = static_cast<unsigned>(Kind) + 1; if (init) *init = finder.InitExpr; } return Kind; } SourceRange DestructorDecl::getSourceRange() const { if (getBodyKind() == BodyKind::Unparsed || getBodyKind() == BodyKind::Skipped) return { getDestructorLoc(), BodyRange.End }; if (getBodyKind() == BodyKind::None) return getDestructorLoc(); return { getDestructorLoc(), getBody()->getEndLoc() }; } PrecedenceGroupDecl * PrecedenceGroupDecl::create(DeclContext *dc, SourceLoc precedenceGroupLoc, SourceLoc nameLoc, Identifier name, SourceLoc lbraceLoc, SourceLoc associativityKeywordLoc, SourceLoc associativityValueLoc, Associativity associativity, SourceLoc assignmentKeywordLoc, SourceLoc assignmentValueLoc, bool isAssignment, SourceLoc higherThanLoc, ArrayRef<Relation> higherThan, SourceLoc lowerThanLoc, ArrayRef<Relation> lowerThan, SourceLoc rbraceLoc) { void *memory = dc->getASTContext().Allocate(sizeof(PrecedenceGroupDecl) + (higherThan.size() + lowerThan.size()) * sizeof(Relation), alignof(PrecedenceGroupDecl)); return new (memory) PrecedenceGroupDecl(dc, precedenceGroupLoc, nameLoc, name, lbraceLoc, associativityKeywordLoc, associativityValueLoc, associativity, assignmentKeywordLoc, assignmentValueLoc, isAssignment, higherThanLoc, higherThan, lowerThanLoc, lowerThan, rbraceLoc); } PrecedenceGroupDecl::PrecedenceGroupDecl(DeclContext *dc, SourceLoc precedenceGroupLoc, SourceLoc nameLoc, Identifier name, SourceLoc lbraceLoc, SourceLoc associativityKeywordLoc, SourceLoc associativityValueLoc, Associativity associativity, SourceLoc assignmentKeywordLoc, SourceLoc assignmentValueLoc, bool isAssignment, SourceLoc higherThanLoc, ArrayRef<Relation> higherThan, SourceLoc lowerThanLoc, ArrayRef<Relation> lowerThan, SourceLoc rbraceLoc) : Decl(DeclKind::PrecedenceGroup, dc), PrecedenceGroupLoc(precedenceGroupLoc), NameLoc(nameLoc), LBraceLoc(lbraceLoc), RBraceLoc(rbraceLoc), AssociativityKeywordLoc(associativityKeywordLoc), AssociativityValueLoc(associativityValueLoc), AssignmentKeywordLoc(assignmentKeywordLoc), AssignmentValueLoc(assignmentValueLoc), HigherThanLoc(higherThanLoc), LowerThanLoc(lowerThanLoc), Name(name), NumHigherThan(higherThan.size()), NumLowerThan(lowerThan.size()) { Bits.PrecedenceGroupDecl.Associativity = unsigned(associativity); Bits.PrecedenceGroupDecl.IsAssignment = isAssignment; memcpy(getHigherThanBuffer(), higherThan.data(), higherThan.size() * sizeof(Relation)); memcpy(getLowerThanBuffer(), lowerThan.data(), lowerThan.size() * sizeof(Relation)); } bool FuncDecl::isDeferBody() const { return getName() == getASTContext().getIdentifier("$defer"); } bool FuncDecl::isPotentialIBActionTarget() const { return isInstanceMember() && getDeclContext()->getAsClassOrClassExtensionContext() && !isa<AccessorDecl>(this); } Type TypeBase::getSwiftNewtypeUnderlyingType() { auto structDecl = getStructOrBoundGenericStruct(); if (!structDecl) return {}; // Make sure the clang node has swift_newtype attribute auto clangNode = structDecl->getClangDecl(); if (!clangNode || !clangNode->hasAttr<clang::SwiftNewtypeAttr>()) return {}; // Underlying type is the type of rawValue for (auto member : structDecl->getMembers()) if (auto varDecl = dyn_cast<VarDecl>(member)) if (varDecl->getName() == getASTContext().Id_rawValue) return varDecl->getType(); return {}; } Type ClassDecl::getSuperclass() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(SuperclassTypeRequest{const_cast<ClassDecl *>(this)}); } ClassDecl *ClassDecl::getSuperclassDecl() const { ASTContext &ctx = getASTContext(); return ctx.evaluator(SuperclassDeclRequest{const_cast<ClassDecl *>(this)}); } void ClassDecl::setSuperclass(Type superclass) { assert((!superclass || !superclass->hasArchetype()) && "superclass must be interface type"); LazySemanticInfo.Superclass.setPointerAndInt(superclass, true); } ClangNode Decl::getClangNodeImpl() const { assert(Bits.Decl.FromClang); void * const *ptr = nullptr; switch (getKind()) { #define DECL(Id, Parent) \ case DeclKind::Id: \ ptr = reinterpret_cast<void * const*>(static_cast<const Id##Decl*>(this)); \ break; #include "swift/AST/DeclNodes.def" } return ClangNode::getFromOpaqueValue(*(ptr - 1)); } void Decl::setClangNode(ClangNode Node) { Bits.Decl.FromClang = true; // The extra/preface memory is allocated by the importer. void **ptr = nullptr; switch (getKind()) { #define DECL(Id, Parent) \ case DeclKind::Id: \ ptr = reinterpret_cast<void **>(static_cast<Id##Decl*>(this)); \ break; #include "swift/AST/DeclNodes.def" } *(ptr - 1) = Node.getOpaqueValue(); } // See swift/Basic/Statistic.h for declaration: this enables tracing Decls, is // defined here to avoid too much layering violation / circular linkage // dependency. struct DeclTraceFormatter : public UnifiedStatsReporter::TraceFormatter { void traceName(const void *Entity, raw_ostream &OS) const { if (!Entity) return; const Decl *D = static_cast<const Decl *>(Entity); if (auto const *VD = dyn_cast<const ValueDecl>(D)) { VD->getFullName().print(OS, false); } else { OS << "<" << Decl::getDescriptiveKindName(D->getDescriptiveKind()) << ">"; } } void traceLoc(const void *Entity, SourceManager *SM, clang::SourceManager *CSM, raw_ostream &OS) const { if (!Entity) return; const Decl *D = static_cast<const Decl *>(Entity); D->getSourceRange().print(OS, *SM, false); } }; static DeclTraceFormatter TF; template<> const UnifiedStatsReporter::TraceFormatter* FrontendStatsTracer::getTraceFormatter<const Decl *>() { return &TF; } TypeOrExtensionDecl::TypeOrExtensionDecl(NominalTypeDecl *D) : Decl(D) {} TypeOrExtensionDecl::TypeOrExtensionDecl(ExtensionDecl *D) : Decl(D) {} Decl *TypeOrExtensionDecl::getAsDecl() const { if (auto NTD = Decl.dyn_cast<NominalTypeDecl *>()) return NTD; return Decl.get<ExtensionDecl *>(); } DeclContext *TypeOrExtensionDecl::getAsDeclContext() const { return getAsDecl()->getInnermostDeclContext(); } NominalTypeDecl *TypeOrExtensionDecl::getBaseNominal() const { return getAsDeclContext()->getAsNominalTypeOrNominalTypeExtensionContext(); } bool TypeOrExtensionDecl::isNull() const { return Decl.isNull(); } void swift::simple_display(llvm::raw_ostream &out, const ValueDecl *decl) { if (decl) decl->dumpRef(out); else out << "(null)"; }