diff --git a/Makefile.common b/Makefile.common index 1dcd853..8085bf4 100644 --- a/Makefile.common +++ b/Makefile.common @@ -1,14 +1,20 @@ +LIBRETRO_COMM_DIR := $(CORE_DIR)/libretro/libretro-common + INCFLAGS := -I$(CORE_DIR) \ -I$(CORE_DIR)/atari800/src \ -I$(CORE_DIR)/libretro \ - -I$(CORE_DIR)/libretro/libco + -I$(LIBRETRO_COMM_DIR)/include ifeq ($(STATIC_LINKING), 1) INCFLAGS += -I$(CORE_DIR)/libretro/include endif SOURCES_C := \ - $(CORE_DIR)/libretro/libco/libco.c + $(LIBRETRO_COMM_DIR)/libco/libco.c + +SOURCES_C += $(LIBRETRO_COMM_DIR)/compat/compat_strl.c \ + $(LIBRETRO_COMM_DIR)/compat/compat_strcasestr.c \ + $(LIBRETRO_COMM_DIR)/file/file_path.c SOURCES_C += \ $(CORE_DIR)/libretro/libretro-core.c \ diff --git a/atari800/src/devices.c b/atari800/src/devices.c index 3d79a82..72afa16 100644 --- a/atari800/src/devices.c +++ b/atari800/src/devices.c @@ -432,9 +432,15 @@ static int Devices_MakeDirectory(const char *filename) #define DO_MKDIR #elif defined(HAVE_MKDIR) - +#ifdef __LIBRETRO__ +#include +#endif static int Devices_MakeDirectory(const char *filename) { +#ifdef __LIBRETRO__ + return path_mkdir(filename)==1; +#else + #ifdef __WIN32__ #define MKDIR_TAKES_ONE_ARG 1 #endif @@ -443,6 +449,8 @@ static int Devices_MakeDirectory(const char *filename) , 0777 #endif ) == 0; + +#endif } #define DO_MKDIR diff --git a/libretro/libco/libco.c b/libretro/libco/libco.c deleted file mode 100644 index 4cc65b2..0000000 --- a/libretro/libco/libco.c +++ /dev/null @@ -1,34 +0,0 @@ -/* - libco - auto-selection module - license: public domain -*/ - -#if defined _MSC_VER - #include - #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) - #include "fiber.c" - #elif defined _M_IX86 - #include "x86.c" - #elif defined _M_AMD64 - #include "amd64.c" - #else - #include "fiber.c" - #endif -#elif defined __GNUC__ - #if defined __i386__ - #include "x86.c" - #elif defined __amd64__ - #include "amd64.c" - #elif defined _ARCH_PPC - #include "ppc.c" - #elif defined VITA - #include "scefiber.c" - #elif defined(__ARM_EABI__) || defined(__arm__) - #include "armeabi.c" - #else - #include "sjlj.c" - #endif -#else - #error "libco: unsupported processor, compiler or operating system" -#endif diff --git a/libretro/libretro-common/compat/compat_fnmatch.c b/libretro/libretro-common/compat/compat_fnmatch.c new file mode 100644 index 0000000..110f451 --- /dev/null +++ b/libretro/libretro-common/compat/compat_fnmatch.c @@ -0,0 +1,159 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (compat_fnmatch.c). + * --------------------------------------------------------------------------------------- + * + * 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. + */ + +#if __TEST_FNMATCH__ +#include +#endif +#include + +#include + +/* Implemnentation of fnmatch(3) so it can be + * distributed to non *nix platforms. + * + * No flags are implemented ATM. + * We don't use them. Add flags as needed. */ + +int rl_fnmatch(const char *pattern, const char *string, int flags) +{ + int rv; + const char *c = NULL; + int charmatch = 0; + + for (c = pattern; *c != '\0'; c++) + { + /* String ended before pattern */ + if ((*c != '*') && (*string == '\0')) + return FNM_NOMATCH; + + switch (*c) + { + /* Match any number of unknown chars */ + case '*': + /* Find next node in the pattern + * ignoring multiple asterixes + */ + do { + c++; + if (*c == '\0') + return 0; + } while (*c == '*'); + + /* Match the remaining pattern + * ignoring more and more characters. */ + do { + /* We reached the end of the string without a + * match. There is a way to optimize this by + * calculating the minimum chars needed to + * match the remaining pattern but I don't + * think it is worth the work ATM. + */ + if (*string == '\0') + return FNM_NOMATCH; + + rv = rl_fnmatch(c, string, flags); + string++; + } while (rv != 0); + + return 0; + /* Match char from list */ + case '[': + charmatch = 0; + for (c++; *c != ']'; c++) + { + /* Bad format */ + if (*c == '\0') + return FNM_NOMATCH; + + /* Match already found */ + if (charmatch) + continue; + + if (*c == *string) + charmatch = 1; + } + + /* No match in list */ + if (!charmatch) + return FNM_NOMATCH; + + string++; + break; + /* Has any character */ + case '?': + string++; + break; + /* Match following character verbatim */ + case '\\': + c++; + /* Dangling escape at end of pattern. + * FIXME: Was c == '\0' (makes no sense). + * Not sure if c == NULL or *c == '\0' + * is intended. Assuming *c due to c++ right before. */ + if (*c == '\0') + return FNM_NOMATCH; + default: + if (*c != *string) + return FNM_NOMATCH; + string++; + } + } + + /* End of string and end of pattend */ + if (*string == '\0') + return 0; + return FNM_NOMATCH; +} + +#if __TEST_FNMATCH__ +int main(void) +{ + assert(rl_fnmatch("TEST", "TEST", 0) == 0); + assert(rl_fnmatch("TE?T", "TEST", 0) == 0); + assert(rl_fnmatch("TE[Ssa]T", "TEST", 0) == 0); + assert(rl_fnmatch("TE[Ssda]T", "TEsT", 0) == 0); + assert(rl_fnmatch("TE[Ssda]T", "TEdT", 0) == 0); + assert(rl_fnmatch("TE[Ssda]T", "TEaT", 0) == 0); + assert(rl_fnmatch("TEST*", "TEST", 0) == 0); + assert(rl_fnmatch("TEST**", "TEST", 0) == 0); + assert(rl_fnmatch("TE*ST*", "TEST", 0) == 0); + assert(rl_fnmatch("TE**ST*", "TEST", 0) == 0); + assert(rl_fnmatch("TE**ST*", "TExST", 0) == 0); + assert(rl_fnmatch("TE**ST", "TEST", 0) == 0); + assert(rl_fnmatch("TE**ST", "TExST", 0) == 0); + assert(rl_fnmatch("TE\\**ST", "TE*xST", 0) == 0); + assert(rl_fnmatch("*.*", "test.jpg", 0) == 0); + assert(rl_fnmatch("*.jpg", "test.jpg", 0) == 0); + assert(rl_fnmatch("*.[Jj][Pp][Gg]", "test.jPg", 0) == 0); + assert(rl_fnmatch("*.[Jj]*[Gg]", "test.jPg", 0) == 0); + assert(rl_fnmatch("TEST?", "TEST", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TES[asd", "TEST", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TEST\\", "TEST", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TEST*S", "TEST", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TE**ST", "TExT", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TE\\*T", "TExT", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TES?", "TES", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TE", "TEST", 0) == FNM_NOMATCH); + assert(rl_fnmatch("TEST!", "TEST", 0) == FNM_NOMATCH); + assert(rl_fnmatch("DSAD", "TEST", 0) == FNM_NOMATCH); +} +#endif diff --git a/libretro/libretro-common/compat/compat_getopt.c b/libretro/libretro-common/compat/compat_getopt.c new file mode 100644 index 0000000..95d1bce --- /dev/null +++ b/libretro/libretro-common/compat/compat_getopt.c @@ -0,0 +1,219 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (compat_getopt.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +char *optarg; +int optind, opterr, optopt; + +static bool is_short_option(const char *str) +{ + return str[0] == '-' && str[1] != '-'; +} + +static bool is_long_option(const char *str) +{ + return str[0] == '-' && str[1] == '-'; +} + +static int find_short_index(char * const *argv) +{ + int idx; + for (idx = 0; argv[idx]; idx++) + { + if (is_short_option(argv[idx])) + return idx; + } + + return -1; +} + +static int find_long_index(char * const *argv) +{ + int idx; + for (idx = 0; argv[idx]; idx++) + { + if (is_long_option(argv[idx])) + return idx; + } + + return -1; +} + +static int parse_short(const char *optstring, char * const *argv) +{ + bool extra_opt, takes_arg, embedded_arg; + const char *opt = NULL; + char arg = argv[0][1]; + + if (arg == ':') + return '?'; + + opt = strchr(optstring, arg); + if (!opt) + return '?'; + + extra_opt = argv[0][2]; + takes_arg = opt[1] == ':'; + + /* If we take an argument, and we see additional characters, + * this is in fact the argument (i.e. -cfoo is same as -c foo). */ + embedded_arg = extra_opt && takes_arg; + + if (takes_arg) + { + if (embedded_arg) + { + optarg = argv[0] + 2; + optind++; + } + else + { + optarg = argv[1]; + optind += 2; + } + + return optarg ? opt[0] : '?'; + } + + if (embedded_arg) + { + /* If we see additional characters, + * and they don't take arguments, this + * means we have multiple flags in one. */ + memmove(&argv[0][1], &argv[0][2], strlen(&argv[0][2]) + 1); + return opt[0]; + } + + optind++; + return opt[0]; +} + +static int parse_long(const struct option *longopts, char * const *argv) +{ + size_t indice; + const struct option *opt = NULL; + for (indice = 0; longopts[indice].name; indice++) + { + if (!strcmp(longopts[indice].name, &argv[0][2])) + { + opt = &longopts[indice]; + break; + } + } + + if (!opt) + return '?'; + + /* getopt_long has an "optional" arg, but we don't bother with that. */ + if (opt->has_arg && !argv[1]) + return '?'; + + if (opt->has_arg) + { + optarg = argv[1]; + optind += 2; + } + else + optind++; + + if (opt->flag) + { + *opt->flag = opt->val; + return 0; + } + + return opt->val; +} + +static void shuffle_block(char **begin, char **last, char **end) +{ + ptrdiff_t len = last - begin; + const char **tmp = (const char**)calloc(len, sizeof(const char*)); + + retro_assert(tmp); + + memcpy((void*)tmp, begin, len * sizeof(const char*)); + memmove(begin, last, (end - last) * sizeof(const char*)); + memcpy(end - len, tmp, len * sizeof(const char*)); + + free((void*)tmp); +} + +int getopt_long(int argc, char *argv[], + const char *optstring, const struct option *longopts, int *longindex) +{ + int short_index, long_index; + + (void)longindex; + + if (optind == 0) + optind = 1; + + if (argc < 2) + return -1; + + short_index = find_short_index(&argv[optind]); + long_index = find_long_index(&argv[optind]); + + /* We're done here. */ + if (short_index == -1 && long_index == -1) + return -1; + + /* Reorder argv so that non-options come last. + * Non-POSIXy, but that's what getopt does by default. */ + if ((short_index > 0) && ((short_index < long_index) || (long_index == -1))) + { + shuffle_block(&argv[optind], &argv[optind + short_index], &argv[argc]); + short_index = 0; + } + else if ((long_index > 0) && ((long_index < short_index) + || (short_index == -1))) + { + shuffle_block(&argv[optind], &argv[optind + long_index], &argv[argc]); + long_index = 0; + } + + retro_assert(short_index == 0 || long_index == 0); + + if (short_index == 0) + return parse_short(optstring, &argv[optind]); + if (long_index == 0) + return parse_long(longopts, &argv[optind]); + + return '?'; +} diff --git a/libretro/libretro-common/compat/compat_ifaddrs.c b/libretro/libretro-common/compat/compat_ifaddrs.c new file mode 100644 index 0000000..40f4da0 --- /dev/null +++ b/libretro/libretro-common/compat/compat_ifaddrs.c @@ -0,0 +1,619 @@ +/* +Copyright (c) 2013, Kenneth MacKay +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +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. +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct NetlinkList +{ + struct NetlinkList *m_next; + struct nlmsghdr *m_data; + unsigned int m_size; +} NetlinkList; + +static int netlink_socket(void) +{ + struct sockaddr_nl l_addr; + int l_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + + if(l_socket < 0) + return -1; + + memset(&l_addr, 0, sizeof(l_addr)); + l_addr.nl_family = AF_NETLINK; + if(bind(l_socket, (struct sockaddr *)&l_addr, sizeof(l_addr)) < 0) + { + close(l_socket); + return -1; + } + + return l_socket; +} + +static int netlink_send(int p_socket, int p_request) +{ + struct + { + struct nlmsghdr m_hdr; + struct rtgenmsg m_msg; + } l_data; + struct sockaddr_nl l_addr; + + memset(&l_data, 0, sizeof(l_data)); + + l_data.m_hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)); + l_data.m_hdr.nlmsg_type = p_request; + l_data.m_hdr.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; + l_data.m_hdr.nlmsg_pid = 0; + l_data.m_hdr.nlmsg_seq = p_socket; + l_data.m_msg.rtgen_family = AF_UNSPEC; + + memset(&l_addr, 0, sizeof(l_addr)); + l_addr.nl_family = AF_NETLINK; + return (sendto(p_socket, &l_data.m_hdr, l_data.m_hdr.nlmsg_len, 0, (struct sockaddr *)&l_addr, sizeof(l_addr))); +} + +static int netlink_recv(int p_socket, void *p_buffer, size_t p_len) +{ + struct msghdr l_msg; + struct iovec l_iov = { p_buffer, p_len }; + struct sockaddr_nl l_addr; + + for(;;) + { + l_msg.msg_name = (void *)&l_addr; + l_msg.msg_namelen = sizeof(l_addr); + l_msg.msg_iov = &l_iov; + l_msg.msg_iovlen = 1; + l_msg.msg_control = NULL; + l_msg.msg_controllen = 0; + l_msg.msg_flags = 0; + int l_result = recvmsg(p_socket, &l_msg, 0); + + if(l_result < 0) + { + if(errno == EINTR) + continue; + return -2; + } + + if(l_msg.msg_flags & MSG_TRUNC) /* buffer too small */ + return -1; + return l_result; + } +} + +static struct nlmsghdr *getNetlinkResponse(int p_socket, int *p_size, int *p_done) +{ + size_t l_size = 4096; + void *l_buffer = NULL; + + for(;;) + { + free(l_buffer); + l_buffer = malloc(l_size); + if (l_buffer == NULL) + return NULL; + + int l_read = netlink_recv(p_socket, l_buffer, l_size); + *p_size = l_read; + + if(l_read == -2) + { + free(l_buffer); + return NULL; + } + + if(l_read >= 0) + { + pid_t l_pid = getpid(); + struct nlmsghdr *l_hdr; + for(l_hdr = (struct nlmsghdr *)l_buffer; NLMSG_OK(l_hdr, (unsigned int)l_read); l_hdr = (struct nlmsghdr *)NLMSG_NEXT(l_hdr, l_read)) + { + if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) + continue; + + if(l_hdr->nlmsg_type == NLMSG_DONE) + { + *p_done = 1; + break; + } + + if(l_hdr->nlmsg_type == NLMSG_ERROR) + { + free(l_buffer); + return NULL; + } + } + return l_buffer; + } + + l_size *= 2; + } +} + +static NetlinkList *newListItem(struct nlmsghdr *p_data, unsigned int p_size) +{ + NetlinkList *l_item = malloc(sizeof(NetlinkList)); + if (l_item == NULL) + return NULL; + + l_item->m_next = NULL; + l_item->m_data = p_data; + l_item->m_size = p_size; + return l_item; +} + +static void freeResultList(NetlinkList *p_list) +{ + NetlinkList *l_cur; + while(p_list) + { + l_cur = p_list; + p_list = p_list->m_next; + free(l_cur->m_data); + free(l_cur); + } +} + +static NetlinkList *getResultList(int p_socket, int p_request) +{ + if(netlink_send(p_socket, p_request) < 0) + return NULL; + + NetlinkList *l_list = NULL; + NetlinkList *l_end = NULL; + int l_size; + int l_done = 0; + while(!l_done) + { + NetlinkList *l_item = NULL; + struct nlmsghdr *l_hdr = getNetlinkResponse(p_socket, &l_size, &l_done); + if(!l_hdr) + goto error; + + l_item = newListItem(l_hdr, l_size); + if (!l_item) + goto error; + + if(!l_list) + l_list = l_item; + else + l_end->m_next = l_item; + l_end = l_item; + } + + return l_list; + +error: + freeResultList(l_list); + return NULL; +} + +static size_t maxSize(size_t a, size_t b) +{ + return (a > b ? a : b); +} + +static size_t calcAddrLen(sa_family_t p_family, int p_dataSize) +{ + switch(p_family) + { + case AF_INET: + return sizeof(struct sockaddr_in); + case AF_INET6: + return sizeof(struct sockaddr_in6); + case AF_PACKET: + return maxSize(sizeof(struct sockaddr_ll), offsetof(struct sockaddr_ll, sll_addr) + p_dataSize); + default: + break; + } + + return maxSize(sizeof(struct sockaddr), offsetof(struct sockaddr, sa_data) + p_dataSize); +} + +static void makeSockaddr(sa_family_t p_family, struct sockaddr *p_dest, void *p_data, size_t p_size) +{ + switch(p_family) + { + case AF_INET: + memcpy(&((struct sockaddr_in*)p_dest)->sin_addr, p_data, p_size); + break; + case AF_INET6: + memcpy(&((struct sockaddr_in6*)p_dest)->sin6_addr, p_data, p_size); + break; + case AF_PACKET: + memcpy(((struct sockaddr_ll*)p_dest)->sll_addr, p_data, p_size); + ((struct sockaddr_ll*)p_dest)->sll_halen = p_size; + break; + default: + memcpy(p_dest->sa_data, p_data, p_size); + break; + } + p_dest->sa_family = p_family; +} + +static void addToEnd(struct ifaddrs **p_resultList, struct ifaddrs *p_entry) +{ + if(!*p_resultList) + *p_resultList = p_entry; + else + { + struct ifaddrs *l_cur = *p_resultList; + while(l_cur->ifa_next) + l_cur = l_cur->ifa_next; + l_cur->ifa_next = p_entry; + } +} + +static int interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList) +{ + struct ifaddrs *l_entry = NULL; + struct rtattr *l_rta = NULL; + struct ifinfomsg *l_info = (struct ifinfomsg *)NLMSG_DATA(p_hdr); + size_t l_nameSize = 0; + size_t l_addrSize = 0; + size_t l_dataSize = 0; + size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg)); + + for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) + { + size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); + switch(l_rta->rta_type) + { + case IFLA_ADDRESS: + case IFLA_BROADCAST: + l_addrSize += NLMSG_ALIGN(calcAddrLen(AF_PACKET, l_rtaDataSize)); + break; + case IFLA_IFNAME: + l_nameSize += NLMSG_ALIGN(l_rtaSize + 1); + break; + case IFLA_STATS: + l_dataSize += NLMSG_ALIGN(l_rtaSize); + break; + default: + break; + } + } + + l_entry = malloc(sizeof(struct ifaddrs) + sizeof(int) + l_nameSize + l_addrSize + l_dataSize); + if (l_entry == NULL) + return -1; + + memset(l_entry, 0, sizeof(struct ifaddrs)); + l_entry->ifa_name = ""; + + char *l_index = ((char *)l_entry) + sizeof(struct ifaddrs); + char *l_name = l_index + sizeof(int); + char *l_addr = l_name + l_nameSize; + char *l_data = l_addr + l_addrSize; + + // save the interface index so we can look it up when handling the addresses. + memcpy(l_index, &l_info->ifi_index, sizeof(int)); + + l_entry->ifa_flags = l_info->ifi_flags; + + l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg)); + for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) + { + void *l_rtaData = RTA_DATA(l_rta); + size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); + switch(l_rta->rta_type) + { + case IFLA_ADDRESS: + case IFLA_BROADCAST: + { + size_t l_addrLen = calcAddrLen(AF_PACKET, l_rtaDataSize); + makeSockaddr(AF_PACKET, (struct sockaddr *)l_addr, l_rtaData, l_rtaDataSize); + ((struct sockaddr_ll *)l_addr)->sll_ifindex = l_info->ifi_index; + ((struct sockaddr_ll *)l_addr)->sll_hatype = l_info->ifi_type; + if(l_rta->rta_type == IFLA_ADDRESS) + l_entry->ifa_addr = (struct sockaddr *)l_addr; + else + l_entry->ifa_broadaddr = (struct sockaddr *)l_addr; + l_addr += NLMSG_ALIGN(l_addrLen); + break; + } + case IFLA_IFNAME: + strncpy(l_name, l_rtaData, l_rtaDataSize); + l_name[l_rtaDataSize] = '\0'; + l_entry->ifa_name = l_name; + break; + case IFLA_STATS: + memcpy(l_data, l_rtaData, l_rtaDataSize); + l_entry->ifa_data = l_data; + break; + default: + break; + } + } + + addToEnd(p_resultList, l_entry); + return 0; +} + +static struct ifaddrs *findInterface(int p_index, struct ifaddrs **p_links, int p_numLinks) +{ + int l_num = 0; + struct ifaddrs *l_cur = *p_links; + while(l_cur && l_num < p_numLinks) + { + int l_index; + char *l_indexPtr = ((char *)l_cur) + sizeof(struct ifaddrs); + + memcpy(&l_index, l_indexPtr, sizeof(int)); + if(l_index == p_index) + return l_cur; + + l_cur = l_cur->ifa_next; + ++l_num; + } + return NULL; +} + +static int interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, int p_numLinks) +{ + size_t l_nameSize = 0; + size_t l_addrSize = 0; + int l_addedNetmask = 0; + struct ifaddrmsg *l_info = (struct ifaddrmsg *)NLMSG_DATA(p_hdr); + struct ifaddrs *l_interface = findInterface(l_info->ifa_index, p_resultList, p_numLinks); + + if(l_info->ifa_family == AF_PACKET) + return 0; + + size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg)); + struct rtattr *l_rta; + + for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) + { + size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); + + switch(l_rta->rta_type) + { + case IFA_ADDRESS: + case IFA_LOCAL: + if((l_info->ifa_family == AF_INET || l_info->ifa_family == AF_INET6) && !l_addedNetmask) + { + /* make room for netmask */ + l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); + l_addedNetmask = 1; + } + case IFA_BROADCAST: + l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); + break; + case IFA_LABEL: + l_nameSize += NLMSG_ALIGN(l_rtaSize + 1); + break; + default: + break; + } + } + + struct ifaddrs *l_entry = malloc(sizeof(struct ifaddrs) + l_nameSize + l_addrSize); + if (l_entry == NULL) + return -1; + + memset(l_entry, 0, sizeof(struct ifaddrs)); + l_entry->ifa_name = (l_interface ? l_interface->ifa_name : ""); + + char *l_name = ((char *)l_entry) + sizeof(struct ifaddrs); + char *l_addr = l_name + l_nameSize; + + l_entry->ifa_flags = l_info->ifa_flags; + if(l_interface) + l_entry->ifa_flags |= l_interface->ifa_flags; + + l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg)); + for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) + { + void *l_rtaData = RTA_DATA(l_rta); + size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); + switch(l_rta->rta_type) + { + case IFA_ADDRESS: + case IFA_BROADCAST: + case IFA_LOCAL: + { + size_t l_addrLen = calcAddrLen(l_info->ifa_family, l_rtaDataSize); + makeSockaddr(l_info->ifa_family, (struct sockaddr *)l_addr, l_rtaData, l_rtaDataSize); + if(l_info->ifa_family == AF_INET6) + { + if(IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)l_rtaData) || IN6_IS_ADDR_MC_LINKLOCAL((struct in6_addr *)l_rtaData)) + ((struct sockaddr_in6 *)l_addr)->sin6_scope_id = l_info->ifa_index; + } + + if(l_rta->rta_type == IFA_ADDRESS) + { + /* apparently in a point-to-point network IFA_ADDRESS + * contains the dest address and IFA_LOCAL contains the local address */ + if(l_entry->ifa_addr) + l_entry->ifa_dstaddr = (struct sockaddr *)l_addr; + else + l_entry->ifa_addr = (struct sockaddr *)l_addr; + } + else if(l_rta->rta_type == IFA_LOCAL) + { + if(l_entry->ifa_addr) + l_entry->ifa_dstaddr = l_entry->ifa_addr; + l_entry->ifa_addr = (struct sockaddr *)l_addr; + } + else + l_entry->ifa_broadaddr = (struct sockaddr *)l_addr; + l_addr += NLMSG_ALIGN(l_addrLen); + break; + } + case IFA_LABEL: + strncpy(l_name, l_rtaData, l_rtaDataSize); + l_name[l_rtaDataSize] = '\0'; + l_entry->ifa_name = l_name; + break; + default: + break; + } + } + + if(l_entry->ifa_addr && + ( l_entry->ifa_addr->sa_family == AF_INET + || l_entry->ifa_addr->sa_family == AF_INET6)) + { + unsigned i; + char l_mask[16]; + unsigned l_maxPrefix = (l_entry->ifa_addr->sa_family == AF_INET + ? 32 : 128); + unsigned l_prefix = (l_info->ifa_prefixlen > l_maxPrefix + ? l_maxPrefix : l_info->ifa_prefixlen); + + l_mask[0] = '\0'; + + for(i=0; i<(l_prefix/8); ++i) + l_mask[i] = 0xff; + if(l_prefix % 8) + l_mask[i] = 0xff << (8 - (l_prefix % 8)); + + makeSockaddr(l_entry->ifa_addr->sa_family, + (struct sockaddr *)l_addr, l_mask, l_maxPrefix / 8); + l_entry->ifa_netmask = (struct sockaddr *)l_addr; + } + + addToEnd(p_resultList, l_entry); + return 0; +} + +static int interpretLinks(int p_socket, NetlinkList *p_netlinkList, + struct ifaddrs **p_resultList) +{ + int l_numLinks = 0; + pid_t l_pid = getpid(); + for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next) + { + struct nlmsghdr *l_hdr = NULL; + unsigned int l_nlsize = p_netlinkList->m_size; + + for(l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize)) + { + if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) + continue; + + if(l_hdr->nlmsg_type == NLMSG_DONE) + break; + + if(l_hdr->nlmsg_type == RTM_NEWLINK) + { + if(interpretLink(l_hdr, p_resultList) == -1) + return -1; + ++l_numLinks; + } + } + } + return l_numLinks; +} + +static int interpretAddrs(int p_socket, NetlinkList *p_netlinkList, + struct ifaddrs **p_resultList, int p_numLinks) +{ + pid_t l_pid = getpid(); + for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next) + { + struct nlmsghdr *l_hdr = NULL; + unsigned int l_nlsize = p_netlinkList->m_size; + + for(l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize)) + { + if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) + continue; + + if(l_hdr->nlmsg_type == NLMSG_DONE) + break; + + if(l_hdr->nlmsg_type == RTM_NEWADDR) + { + if (interpretAddr(l_hdr, p_resultList, p_numLinks) == -1) + return -1; + } + } + } + return 0; +} + +int getifaddrs(struct ifaddrs **ifap) +{ + int l_socket = 0; + int l_result = 0; + if(!ifap) + return -1; + *ifap = NULL; + + l_socket = netlink_socket(); + if(l_socket < 0) + return -1; + + NetlinkList *l_linkResults = getResultList(l_socket, RTM_GETLINK); + if(!l_linkResults) + { + close(l_socket); + return -1; + } + + NetlinkList *l_addrResults = getResultList(l_socket, RTM_GETADDR); + if(!l_addrResults) + { + close(l_socket); + freeResultList(l_linkResults); + return -1; + } + + int l_numLinks = interpretLinks(l_socket, l_linkResults, ifap); + + if(l_numLinks == -1 || interpretAddrs(l_socket, l_addrResults, ifap, l_numLinks) == -1) + l_result = -1; + + freeResultList(l_linkResults); + freeResultList(l_addrResults); + close(l_socket); + return l_result; +} + +void freeifaddrs(struct ifaddrs *ifa) +{ + struct ifaddrs *l_cur = NULL; + + while(ifa) + { + l_cur = ifa; + ifa = ifa->ifa_next; + free(l_cur); + } +} diff --git a/libretro/libretro-common/compat/compat_posix_string.c b/libretro/libretro-common/compat/compat_posix_string.c new file mode 100644 index 0000000..4bddf11 --- /dev/null +++ b/libretro/libretro-common/compat/compat_posix_string.c @@ -0,0 +1,104 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (compat_posix_string.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include + +#include + +#ifdef _WIN32 + +#undef strcasecmp +#undef strdup +#undef isblank +#undef strtok_r +#include +#include +#include +#include + +#include + +int retro_strcasecmp__(const char *a, const char *b) +{ + while (*a && *b) + { + int a_ = tolower(*a); + int b_ = tolower(*b); + + if (a_ != b_) + return a_ - b_; + + a++; + b++; + } + + return tolower(*a) - tolower(*b); +} + +char *retro_strdup__(const char *orig) +{ + size_t len = strlen(orig) + 1; + char *ret = (char*)malloc(len); + if (!ret) + return NULL; + + strlcpy(ret, orig, len); + return ret; +} + +int retro_isblank__(int c) +{ + return (c == ' ') || (c == '\t'); +} + +char *retro_strtok_r__(char *str, const char *delim, char **saveptr) +{ + char *first = NULL; + if (!saveptr || !delim) + return NULL; + + if (str) + *saveptr = str; + + do + { + char *ptr = NULL; + first = *saveptr; + while (*first && strchr(delim, *first)) + *first++ = '\0'; + + if (*first == '\0') + return NULL; + + ptr = first + 1; + + while (*ptr && !strchr(delim, *ptr)) + ptr++; + + *saveptr = ptr + (*ptr ? 1 : 0); + *ptr = '\0'; + } while (strlen(first) == 0); + + return first; +} + +#endif diff --git a/libretro/libretro-common/compat/compat_snprintf.c b/libretro/libretro-common/compat/compat_snprintf.c new file mode 100644 index 0000000..49867de --- /dev/null +++ b/libretro/libretro-common/compat/compat_snprintf.c @@ -0,0 +1,70 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (compat_snprintf.c). + * --------------------------------------------------------------------------------------- + * + * 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. + */ + +/* THIS FILE HAS NOT BEEN VALIDATED ON PLATFORMS BESIDES MSVC */ +#ifdef _MSC_VER + +#include + +#include +#include + +/* http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010 */ + +int c99_vsnprintf_retro__(char *outBuf, size_t size, const char *format, va_list ap) +{ + int count = -1; + + if (size != 0) +#if (_MSC_VER <= 1310) + count = _vsnprintf(outBuf, size, format, ap); +#else + count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); +#endif + if (count == -1) + count = _vscprintf(format, ap); + + return count; +} + +int c99_snprintf_retro__(char *outBuf, size_t size, const char *format, ...) +{ + int count; + va_list ap; + + va_start(ap, format); + count = c99_vsnprintf_retro__(outBuf, size, format, ap); + va_end(ap); + + return count; +} + +int c89_vscprintf_retro__(const char *format, va_list pargs) +{ + int retval; + va_list argcopy; + va_copy(argcopy, pargs); + retval = vsnprintf(NULL, 0, format, argcopy); + va_end(argcopy); + return retval; +} +#endif diff --git a/libretro/libretro-common/compat/compat_strcasestr.c b/libretro/libretro-common/compat/compat_strcasestr.c new file mode 100644 index 0000000..82ce5ac --- /dev/null +++ b/libretro/libretro-common/compat/compat_strcasestr.c @@ -0,0 +1,58 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (compat_strcasestr.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include + +#include + +/* Pretty much strncasecmp. */ +static int casencmp(const char *a, const char *b, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) + { + int a_lower = tolower(a[i]); + int b_lower = tolower(b[i]); + if (a_lower != b_lower) + return a_lower - b_lower; + } + + return 0; +} + +char *strcasestr_retro__(const char *haystack, const char *needle) +{ + size_t i, search_off; + size_t hay_len = strlen(haystack); + size_t needle_len = strlen(needle); + + if (needle_len > hay_len) + return NULL; + + search_off = hay_len - needle_len; + for (i = 0; i <= search_off; i++) + if (!casencmp(haystack + i, needle, needle_len)) + return (char*)haystack + i; + + return NULL; +} diff --git a/libretro/libretro-common/compat/compat_strl.c b/libretro/libretro-common/compat/compat_strl.c new file mode 100644 index 0000000..668b3d9 --- /dev/null +++ b/libretro/libretro-common/compat/compat_strl.c @@ -0,0 +1,62 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (compat_strl.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include + +#include +#include + +/* Implementation of strlcpy()/strlcat() based on OpenBSD. */ + +#ifndef __MACH__ + +size_t strlcpy(char *dest, const char *source, size_t size) +{ + size_t src_size = 0; + size_t n = size; + + if (n) + while (--n && (*dest++ = *source++)) src_size++; + + if (!n) + { + if (size) *dest = '\0'; + while (*source++) src_size++; + } + + return src_size; +} + +size_t strlcat(char *dest, const char *source, size_t size) +{ + size_t len = strlen(dest); + + dest += len; + + if (len > size) + size = 0; + else + size -= len; + + return len + strlcpy(dest, source, size); +} +#endif diff --git a/libretro/libretro-common/file/archive_file.c b/libretro/libretro-common/file/archive_file.c new file mode 100644 index 0000000..4a11045 --- /dev/null +++ b/libretro/libretro-common/file/archive_file.c @@ -0,0 +1,897 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (archive_file.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#include +#include +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifdef HAVE_MMAP +#include +#include +#include + +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +struct file_archive_file_data +{ +#ifdef HAVE_MMAP + int fd; +#endif + void *data; + size_t size; +}; + +static size_t file_archive_size(file_archive_file_data_t *data) +{ + if (!data) + return 0; + return data->size; +} + +static const uint8_t *file_archive_data(file_archive_file_data_t *data) +{ + if (!data) + return NULL; + return (const uint8_t*)data->data; +} + +#ifdef HAVE_MMAP +/* Closes, unmaps and frees. */ +static void file_archive_free(file_archive_file_data_t *data) +{ + if (!data) + return; + + if (data->data) + munmap(data->data, data->size); + if (data->fd >= 0) + close(data->fd); + free(data); +} + +static file_archive_file_data_t* file_archive_open(const char *path) +{ + file_archive_file_data_t *data = (file_archive_file_data_t*)calloc(1, sizeof(*data)); + + if (!data) + return NULL; + + data->fd = open(path, O_RDONLY); + + /* Failed to open archive. */ + if (data->fd < 0) + goto error; + + data->size = path_get_size(path); + if (!data->size) + return data; + + data->data = mmap(NULL, data->size, PROT_READ, MAP_SHARED, data->fd, 0); + if (data->data == MAP_FAILED) + { + data->data = NULL; + + /* Failed to mmap() file */ + goto error; + } + + return data; + +error: + file_archive_free(data); + return NULL; +} +#else + +/* Closes, unmaps and frees. */ +static void file_archive_free(file_archive_file_data_t *data) +{ + if (!data) + return; + if(data->data) + free(data->data); + free(data); +} + +static file_archive_file_data_t* file_archive_open(const char *path) +{ + ssize_t ret = -1; + bool read_from_file = false; + file_archive_file_data_t *data = (file_archive_file_data_t*) + calloc(1, sizeof(*data)); + + if (!data) + return NULL; + + read_from_file = filestream_read_file(path, &data->data, &ret); + + /* Failed to open archive? */ + if (!read_from_file || ret < 0) + goto error; + + data->size = ret; + return data; + +error: + file_archive_free(data); + return NULL; +} +#endif + +static int file_archive_get_file_list_cb( + const char *path, + const char *valid_exts, + const uint8_t *cdata, + unsigned cmode, + uint32_t csize, + uint32_t size, + uint32_t checksum, + struct archive_extract_userdata *userdata) +{ + union string_list_elem_attr attr; + int ret = 0; + struct string_list *ext_list = NULL; + size_t path_len = strlen(path); + + (void)cdata; + (void)cmode; + (void)csize; + (void)size; + (void)checksum; + + attr.i = 0; + + if (!path_len) + return 0; + + if (valid_exts) + ext_list = string_split(valid_exts, "|"); + + if (ext_list) + { + const char *file_ext = NULL; + /* Checks if this entry is a directory or a file. */ + char last_char = path[path_len-1]; + + /* Skip if directory. */ + if (last_char == '/' || last_char == '\\' ) + goto error; + + file_ext = path_get_extension(path); + + if (!file_ext) + goto error; + + if (!string_list_find_elem_prefix(ext_list, ".", file_ext)) + { + /* keep iterating */ + ret = -1; + goto error; + } + + attr.i = RARCH_COMPRESSED_FILE_IN_ARCHIVE; + string_list_free(ext_list); + } + + return string_list_append(userdata->list, path, attr); + +error: + string_list_free(ext_list); + return ret; +} + +static int file_archive_extract_cb(const char *name, const char *valid_exts, + const uint8_t *cdata, + unsigned cmode, uint32_t csize, uint32_t size, + uint32_t checksum, struct archive_extract_userdata *userdata) +{ + const char *ext = path_get_extension(name); + + /* Extract first file that matches our list. */ + if (ext && string_list_find_elem(userdata->ext, ext)) + { + char new_path[PATH_MAX_LENGTH]; + char wanted_file[PATH_MAX_LENGTH]; + const char *delim = NULL; + + new_path[0] = wanted_file[0] = '\0'; + + if (userdata->extraction_directory) + fill_pathname_join(new_path, userdata->extraction_directory, + path_basename(name), sizeof(new_path)); + else + fill_pathname_resolve_relative(new_path, userdata->archive_path, + path_basename(name), sizeof(new_path)); + + userdata->first_extracted_file_path = strdup(new_path); + + delim = path_get_archive_delim(userdata->archive_path); + + if (delim) + { + strlcpy(wanted_file, delim + 1, sizeof(wanted_file)); + + if (!string_is_equal_noncase(userdata->extracted_file_path, + wanted_file)) + return 1; /* keep searching for the right file */ + } + else + strlcpy(wanted_file, userdata->archive_path, sizeof(wanted_file)); + + if (file_archive_perform_mode(new_path, + valid_exts, cdata, cmode, csize, size, + 0, userdata)) + userdata->found_file = true; + + return 0; + } + + return 1; +} + +static int file_archive_parse_file_init(file_archive_transfer_t *state, + const char *file) +{ + char path[PATH_MAX_LENGTH]; + char *last = NULL; + + path[0] = '\0'; + + strlcpy(path, file, sizeof(path)); + + last = (char*)path_get_archive_delim(path); + + if (last) + *last = '\0'; + + state->backend = file_archive_get_file_backend(path); + if (!state->backend) + return -1; + + state->handle = file_archive_open(path); + if (!state->handle) + return -1; + + state->archive_size = (int32_t)file_archive_size(state->handle); + state->data = file_archive_data(state->handle); + state->footer = 0; + state->directory = 0; + + return state->backend->archive_parse_file_init(state, path); +} + +/** + * file_archive_decompress_data_to_file: + * @path : filename path of archive. + * @valid_exts : Valid extensions of archive to be parsed. + * If NULL, allow all. + * @cdata : input data. + * @csize : size of input data. + * @size : output file size + * @checksum : CRC32 checksum from input data. + * + * Decompress data to file. + * + * Returns: true (1) on success, otherwise false (0). + **/ +static int file_archive_decompress_data_to_file( + file_archive_file_handle_t *handle, + int ret, + const char *path, + const char *valid_exts, + const uint8_t *cdata, + uint32_t csize, + uint32_t size, + uint32_t checksum) +{ + if (!handle || ret == -1) + { + ret = 0; + goto end; + } + +#if 0 + handle->real_checksum = handle->backend->stream_crc_calculate( + 0, handle->data, size); + if (handle->real_checksum != checksum) + { + /* File CRC difers from archive CRC. */ + printf("File CRC differs from archive CRC. File: 0x%x, Archive: 0x%x.\n", + (unsigned)handle->real_checksum, (unsigned)checksum); + } +#endif + + if (!filestream_write_file(path, handle->data, size)) + { + ret = false; + goto end; + } + +end: + + if (handle) + { + if (handle->backend) + { + if (handle->backend->stream_free) + handle->backend->stream_free(handle->stream); + } + + if (handle->data) + free(handle->data); + } + + return ret; +} + +void file_archive_parse_file_iterate_stop(file_archive_transfer_t *state) +{ + if (!state || !state->handle) + return; + + state->type = ARCHIVE_TRANSFER_DEINIT; + file_archive_parse_file_iterate(state, NULL, NULL, NULL, NULL, NULL); +} + +int file_archive_parse_file_iterate( + file_archive_transfer_t *state, + bool *returnerr, + const char *file, + const char *valid_exts, + file_archive_file_cb file_cb, + struct archive_extract_userdata *userdata) +{ + if (!state) + return -1; + + switch (state->type) + { + case ARCHIVE_TRANSFER_NONE: + break; + case ARCHIVE_TRANSFER_INIT: + if (file_archive_parse_file_init(state, file) == 0) + { + if (userdata) + { + userdata->context = state->stream; + strlcpy(userdata->archive_path, file, + sizeof(userdata->archive_path)); + } + state->type = ARCHIVE_TRANSFER_ITERATE; + } + else + state->type = ARCHIVE_TRANSFER_DEINIT_ERROR; + break; + case ARCHIVE_TRANSFER_ITERATE: + if (file_archive_get_file_backend(file)) + { + const struct file_archive_file_backend *backend = + file_archive_get_file_backend(file); + int ret = + backend->archive_parse_file_iterate_step(state, + valid_exts, userdata, file_cb); + + if (ret != 1) + state->type = ARCHIVE_TRANSFER_DEINIT; + if (ret == -1) + state->type = ARCHIVE_TRANSFER_DEINIT_ERROR; + + /* early return to prevent deinit from never firing */ + return 0; + } + return -1; + case ARCHIVE_TRANSFER_DEINIT_ERROR: + *returnerr = false; + case ARCHIVE_TRANSFER_DEINIT: + if (state->handle) + { + file_archive_free(state->handle); + state->handle = NULL; + } + + if (state->stream && state->backend) + { + if (state->backend->stream_free) + state->backend->stream_free(state->stream); + + if (state->stream) + free(state->stream); + + state->stream = NULL; + + if (userdata) + userdata->context = NULL; + } + break; + } + + if ( state->type == ARCHIVE_TRANSFER_DEINIT || + state->type == ARCHIVE_TRANSFER_DEINIT_ERROR) + return -1; + + return 0; +} + +/** + * file_archive_walk: + * @file : filename path of archive + * @valid_exts : Valid extensions of archive to be parsed. + * If NULL, allow all. + * @file_cb : file_cb function pointer + * @userdata : userdata to pass to file_cb function pointer. + * + * Low-level file parsing. Enumerates over all files and calls + * file_cb with userdata. + * + * Returns: true (1) on success, otherwise false (0). + **/ +static bool file_archive_walk(const char *file, const char *valid_exts, + file_archive_file_cb file_cb, struct archive_extract_userdata *userdata) +{ + file_archive_transfer_t state; + bool returnerr = true; + + state.type = ARCHIVE_TRANSFER_INIT; + state.archive_size = 0; + state.handle = NULL; + state.stream = NULL; + state.footer = NULL; + state.directory = NULL; + state.data = NULL; + state.backend = NULL; + + for (;;) + { + if (file_archive_parse_file_iterate(&state, &returnerr, file, + valid_exts, file_cb, userdata) != 0) + break; + } + + return returnerr; +} + +int file_archive_parse_file_progress(file_archive_transfer_t *state) +{ + /* FIXME: this estimate is worse than before */ + ptrdiff_t delta = 0; + + if (!state || state->archive_size == 0) + return 0; + + delta = state->directory - state->data; + + return (int)(delta * 100 / state->archive_size); +} + +/** + * file_archive_extract_file: + * @archive_path : filename path to archive. + * @archive_path_size : size of archive. + * @valid_exts : valid extensions for the file. + * @extraction_directory : the directory to extract temporary + * file to. + * + * Extract file from archive. If no file inside the archive is + * specified, the first file found will be used. + * + * Returns : true (1) on success, otherwise false (0). + **/ +bool file_archive_extract_file( + char *archive_path, + size_t archive_path_size, + const char *valid_exts, + const char *extraction_directory, + char *out_path, size_t len) +{ + struct archive_extract_userdata userdata; + bool ret = true; + struct string_list *list = string_split(valid_exts, "|"); + + userdata.archive_path[0] = '\0'; + userdata.first_extracted_file_path = NULL; + userdata.extracted_file_path = NULL; + userdata.extraction_directory = extraction_directory; + userdata.archive_path_size = archive_path_size; + userdata.ext = list; + userdata.list = NULL; + userdata.found_file = false; + userdata.list_only = false; + userdata.context = NULL; + userdata.archive_name[0] = '\0'; + userdata.crc = 0; + userdata.dec = NULL; + + userdata.decomp_state.opt_file = NULL; + userdata.decomp_state.needle = NULL; + userdata.decomp_state.size = 0; + userdata.decomp_state.found = NULL; + + if (!list) + { + ret = false; + goto end; + } + + if (!file_archive_walk(archive_path, valid_exts, + file_archive_extract_cb, &userdata)) + { + /* Parsing file archive failed. */ + ret = false; + goto end; + } + + if (!userdata.found_file) + { + /* Didn't find any file that matched valid extensions + * for libretro implementation. */ + ret = false; + goto end; + } + + if (!string_is_empty(userdata.first_extracted_file_path)) + strlcpy(out_path, userdata.first_extracted_file_path, len); + +end: + if (userdata.first_extracted_file_path) + free(userdata.first_extracted_file_path); + if (list) + string_list_free(list); + return ret; +} + +/** + * file_archive_get_file_list: + * @path : filename path of archive + * + * Returns: string listing of files from archive on success, otherwise NULL. + **/ +struct string_list *file_archive_get_file_list(const char *path, + const char *valid_exts) +{ + int ret; + struct archive_extract_userdata userdata; + + strlcpy(userdata.archive_path, path, sizeof(userdata.archive_path)); + userdata.first_extracted_file_path = NULL; + userdata.extracted_file_path = NULL; + userdata.extraction_directory = NULL; + userdata.archive_path_size = 0; + userdata.ext = NULL; + userdata.list = string_list_new(); + userdata.found_file = false; + userdata.list_only = true; + userdata.context = NULL; + userdata.archive_name[0] = '\0'; + userdata.crc = 0; + userdata.dec = NULL; + + userdata.decomp_state.opt_file = NULL; + userdata.decomp_state.needle = NULL; + userdata.decomp_state.size = 0; + userdata.decomp_state.found = NULL; + + if (!userdata.list) + goto error; + + ret = file_archive_walk(path, valid_exts, + file_archive_get_file_list_cb, &userdata); + + if (ret <= 0) + { + if (ret != -1) + goto error; + } + + return userdata.list; + +error: + if (userdata.list) + string_list_free(userdata.list); + return NULL; +} + +bool file_archive_perform_mode(const char *path, const char *valid_exts, + const uint8_t *cdata, unsigned cmode, uint32_t csize, uint32_t size, + uint32_t crc32, struct archive_extract_userdata *userdata) +{ + switch (cmode) + { + case ARCHIVE_MODE_UNCOMPRESSED: + if (!filestream_write_file(path, cdata, size)) + goto error; + break; + + case ARCHIVE_MODE_COMPRESSED: + { + int ret = 0; + file_archive_file_handle_t handle; + + handle.stream = userdata->context; + handle.data = NULL; + handle.real_checksum = 0; + handle.backend = file_archive_get_file_backend(userdata->archive_path); + + if (!handle.backend) + goto error; + + if (!handle.backend->stream_decompress_data_to_file_init(&handle, + cdata, csize, size)) + goto error; + + do + { + ret = handle.backend->stream_decompress_data_to_file_iterate( + handle.stream); + }while(ret == 0); + + if (!file_archive_decompress_data_to_file(&handle, + ret, path, valid_exts, + cdata, csize, size, crc32)) + goto error; + } + break; + default: + goto error; + } + + return true; + +error: + return false; +} + +/** + * file_archive_filename_split: + * @str : filename to turn into a string list + * + * Creates a new string list based on filename @path, delimited by a hash (#). + * + * Returns: new string list if successful, otherwise NULL. + */ +static struct string_list *file_archive_filename_split(const char *path) +{ + union string_list_elem_attr attr; + struct string_list *list = string_list_new(); + const char *delim = path_get_archive_delim(path); + + attr.i = 0; + + if (delim) + { + /* add archive path to list first */ + if (!string_list_append_n(list, path, (unsigned)(delim - path), attr)) + goto error; + + /* now add the path within the archive */ + delim++; + + if (*delim) + { + if (!string_list_append(list, delim, attr)) + goto error; + } + } + else + if (!string_list_append(list, path, attr)) + goto error; + + return list; + +error: + string_list_free(list); + return NULL; +} + +/* Generic compressed file loader. + * Extracts to buf, unless optional_filename != 0 + * Then extracts to optional_filename and leaves buf alone. + */ +int file_archive_compressed_read( + const char * path, void **buf, + const char* optional_filename, ssize_t *length) +{ + const struct file_archive_file_backend *backend = NULL; + int ret = 0; + struct string_list *str_list = file_archive_filename_split(path); + + /* Safety check. + * If optional_filename and optional_filename + * exists, we simply return 0, + * hoping that optional_filename is the + * same as requested. + */ + if (optional_filename && path_file_exists(optional_filename)) + { + *length = 0; + string_list_free(str_list); + return 1; + } + + /* We assure that there is something after the '#' symbol. + * + * This error condition happens for example, when + * path = /path/to/file.7z, or + * path = /path/to/file.7z# + */ + if (str_list->size <= 1) + goto error; + + backend = file_archive_get_file_backend(str_list->elems[0].data); + + *length = backend->compressed_file_read(str_list->elems[0].data, + str_list->elems[1].data, buf, optional_filename); + + if (*length != -1) + ret = 1; + + string_list_free(str_list); + return ret; + +error: + /* could not extract string and substring. */ + string_list_free(str_list); + *length = 0; + return 0; +} + +const struct file_archive_file_backend *file_archive_get_zlib_file_backend(void) +{ +#ifdef HAVE_ZLIB + return &zlib_backend; +#else + return NULL; +#endif +} + +const struct file_archive_file_backend *file_archive_get_7z_file_backend(void) +{ +#ifdef HAVE_7ZIP + return &sevenzip_backend; +#else + return NULL; +#endif +} + +const struct file_archive_file_backend* file_archive_get_file_backend(const char *path) +{ + char newpath[PATH_MAX_LENGTH]; + const char *file_ext = NULL; + char *last = NULL; + + newpath[0] = '\0'; + + strlcpy(newpath, path, sizeof(newpath)); + + last = (char*)path_get_archive_delim(newpath); + + if (last) + *last = '\0'; + + file_ext = path_get_extension(newpath); + +#ifdef HAVE_7ZIP + if (string_is_equal_noncase(file_ext, "7z")) + return &sevenzip_backend; +#endif + +#ifdef HAVE_ZLIB + if ( string_is_equal_noncase(file_ext, "zip") + || string_is_equal_noncase(file_ext, "apk") + ) + return &zlib_backend; +#endif + + return NULL; +} + +/** + * file_archive_get_file_crc32: + * @path : filename path of archive + * + * Returns: CRC32 of the specified file in the archive, otherwise 0. + * If no path within the archive is specified, the first + * file found inside is used. + **/ +uint32_t file_archive_get_file_crc32(const char *path) +{ + file_archive_transfer_t state; + const struct file_archive_file_backend *backend = file_archive_get_file_backend(path); + struct archive_extract_userdata userdata = {{0}}; + bool returnerr = false; + bool contains_compressed = false; + const char *archive_path = NULL; + + if (!backend) + return 0; + + contains_compressed = path_contains_compressed_file(path); + + if (contains_compressed) + { + archive_path = path_get_archive_delim(path); + + /* move pointer right after the delimiter to give us the path */ + if (archive_path) + archive_path += 1; + } + + state.type = ARCHIVE_TRANSFER_INIT; + state.archive_size = 0; + state.handle = NULL; + state.stream = NULL; + state.footer = NULL; + state.directory = NULL; + state.data = NULL; + state.backend = NULL; + + /* Initialize and open archive first. + Sets next state type to ITERATE. */ + file_archive_parse_file_iterate(&state, + &returnerr, path, NULL, NULL, + &userdata); + + for (;;) + { + /* Now find the first file in the archive. */ + if (state.type == ARCHIVE_TRANSFER_ITERATE) + file_archive_parse_file_iterate(&state, + &returnerr, path, NULL, NULL, + &userdata); + + /* If no path specified within archive, stop after + * finding the first file. + */ + if (!contains_compressed) + break; + + /* Stop when the right file in the archive is found. */ + if (archive_path) + { + if (string_is_equal(userdata.extracted_file_path, archive_path)) + break; + } + else + break; + } + + file_archive_parse_file_iterate_stop(&state); + + if (userdata.crc) + return userdata.crc; + + return 0; +} diff --git a/libretro/libretro-common/file/archive_file_7z.c b/libretro/libretro-common/file/archive_file_7z.c new file mode 100644 index 0000000..7bfb677 --- /dev/null +++ b/libretro/libretro-common/file/archive_file_7z.c @@ -0,0 +1,472 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (archive_file_sevenzip.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../deps/7zip/7z.h" +#include "../../deps/7zip/7zCrc.h" +#include "../../deps/7zip/7zFile.h" + +#define SEVENZIP_MAGIC "7z\xBC\xAF\x27\x1C" +#define SEVENZIP_MAGIC_LEN 6 + +struct sevenzip_context_t { + CFileInStream archiveStream; + CLookToRead lookStream; + ISzAlloc allocImp; + ISzAlloc allocTempImp; + CSzArEx db; + size_t temp_size; + uint32_t block_index; + uint32_t index; + uint32_t packIndex; + uint8_t *output; + file_archive_file_handle_t *handle; +}; + +static void *sevenzip_stream_alloc_impl(void *p, size_t size) +{ + if (size == 0) + return 0; + return malloc(size); +} + +static void sevenzip_stream_free_impl(void *p, void *address) +{ + (void)p; + free(address); +} + +static void *sevenzip_stream_alloc_tmp_impl(void *p, size_t size) +{ + (void)p; + if (size == 0) + return 0; + return malloc(size); +} + +static void* sevenzip_stream_new(void) +{ + struct sevenzip_context_t *sevenzip_context = + (struct sevenzip_context_t*)calloc(1, sizeof(struct sevenzip_context_t)); + + /* These are the allocation routines - currently using + * the non-standard 7zip choices. */ + sevenzip_context->allocImp.Alloc = sevenzip_stream_alloc_impl; + sevenzip_context->allocImp.Free = sevenzip_stream_free_impl; + sevenzip_context->allocTempImp.Alloc = sevenzip_stream_alloc_tmp_impl; + sevenzip_context->allocTempImp.Free = sevenzip_stream_free_impl; + sevenzip_context->block_index = 0xFFFFFFFF; + sevenzip_context->output = NULL; + sevenzip_context->handle = NULL; + + return sevenzip_context; +} + +static void sevenzip_stream_free(void *data) +{ + struct sevenzip_context_t *sevenzip_context = (struct sevenzip_context_t*)data; + + if (!sevenzip_context) + return; + + if (sevenzip_context->output) + { + IAlloc_Free(&sevenzip_context->allocImp, sevenzip_context->output); + sevenzip_context->output = NULL; + sevenzip_context->handle->data = NULL; + } + + SzArEx_Free(&sevenzip_context->db, &sevenzip_context->allocImp); + File_Close(&sevenzip_context->archiveStream.file); +} + +/* Extract the relative path (needle) from a 7z archive + * (path) and allocate a buf for it to write it in. + * If optional_outfile is set, extract to that instead + * and don't allocate buffer. + */ +static int sevenzip_file_read( + const char *path, + const char *needle, void **buf, + const char *optional_outfile) +{ + CFileInStream archiveStream; + CLookToRead lookStream; + ISzAlloc allocImp; + ISzAlloc allocTempImp; + CSzArEx db; + uint8_t *output = 0; + long outsize = -1; + + /*These are the allocation routines. + * Currently using the non-standard 7zip choices. */ + allocImp.Alloc = sevenzip_stream_alloc_impl; + allocImp.Free = sevenzip_stream_free_impl; + allocTempImp.Alloc = sevenzip_stream_alloc_tmp_impl; + allocTempImp.Free = sevenzip_stream_free_impl; + + /* Could not open 7zip archive? */ + if (InFile_Open(&archiveStream.file, path)) + return -1; + + FileInStream_CreateVTable(&archiveStream); + LookToRead_CreateVTable(&lookStream, false); + lookStream.realStream = &archiveStream.s; + LookToRead_Init(&lookStream); + CrcGenerateTable(); + + db.db.PackSizes = NULL; + db.db.PackCRCsDefined = NULL; + db.db.PackCRCs = NULL; + db.db.Folders = NULL; + db.db.Files = NULL; + db.db.NumPackStreams = 0; + db.db.NumFolders = 0; + db.db.NumFiles = 0; + db.startPosAfterHeader = 0; + db.dataPos = 0; + db.FolderStartPackStreamIndex = NULL; + db.PackStreamStartPositions = NULL; + db.FolderStartFileIndex = NULL; + db.FileIndexToFolderIndexMap = NULL; + db.FileNameOffsets = NULL; + db.FileNames.data = NULL; + db.FileNames.size = 0; + + SzArEx_Init(&db); + + if (SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp) == SZ_OK) + { + uint32_t i; + bool file_found = false; + uint16_t *temp = NULL; + size_t temp_size = 0; + uint32_t block_index = 0xFFFFFFFF; + SRes res = SZ_OK; + + for (i = 0; i < db.db.NumFiles; i++) + { + size_t len; + char infile[PATH_MAX_LENGTH]; + size_t offset = 0; + size_t outSizeProcessed = 0; + const CSzFileItem *f = db.db.Files + i; + + /* We skip over everything which is not a directory. + * FIXME: Why continue then if f->IsDir is true?*/ + if (f->IsDir) + continue; + + len = SzArEx_GetFileNameUtf16(&db, i, NULL); + + if (len > temp_size) + { + if (temp) + free(temp); + temp_size = len; + temp = (uint16_t *)malloc(temp_size * sizeof(temp[0])); + + if (temp == 0) + { + res = SZ_ERROR_MEM; + break; + } + } + + SzArEx_GetFileNameUtf16(&db, i, temp); + res = SZ_ERROR_FAIL; + infile[0] = '\0'; + + if (temp) + res = utf16_to_char_string(temp, infile, sizeof(infile)) + ? SZ_OK : SZ_ERROR_FAIL; + + if (string_is_equal(infile, needle)) + { + size_t output_size = 0; + + /*RARCH_LOG_OUTPUT("Opened archive %s. Now trying to extract %s\n", + path, needle);*/ + + /* C LZMA SDK does not support chunked extraction - see here: + * sourceforge.net/p/sevenzip/discussion/45798/thread/6fb59aaf/ + * */ + file_found = true; + res = SzArEx_Extract(&db, &lookStream.s, i, &block_index, + &output, &output_size, &offset, &outSizeProcessed, + &allocImp, &allocTempImp); + + if (res != SZ_OK) + break; /* This goes to the error section. */ + + outsize = outSizeProcessed; + + if (optional_outfile != NULL) + { + const void *ptr = (const void*)(output + offset); + + if (!filestream_write_file(optional_outfile, ptr, outsize)) + { + /*RARCH_ERR("Could not open outfilepath %s.\n", + optional_outfile);*/ + res = SZ_OK; + file_found = true; + outsize = -1; + } + } + else + { + /*We could either use the 7Zip allocated buffer, + * or create our own and use it. + * We would however need to realloc anyways, because RetroArch + * expects a \0 at the end, therefore we allocate new, + * copy and free the old one. */ + *buf = malloc(outsize + 1); + ((char*)(*buf))[outsize] = '\0'; + memcpy(*buf,output + offset,outsize); + } + break; + } + } + + if (temp) + free(temp); + IAlloc_Free(&allocImp, output); + + if (!(file_found && res == SZ_OK)) + { + /* Error handling + * + * Failed to open compressed file inside 7zip archive. + */ + + outsize = -1; + } + } + + SzArEx_Free(&db, &allocImp); + File_Close(&archiveStream.file); + + return (int)outsize; +} + +static bool sevenzip_stream_decompress_data_to_file_init( + file_archive_file_handle_t *handle, + const uint8_t *cdata, uint32_t csize, uint32_t size) +{ + struct sevenzip_context_t *sevenzip_context = + (struct sevenzip_context_t*)handle->stream; + + if (!sevenzip_context) + return false; + + sevenzip_context->handle = handle; + + return true; +} + +static int sevenzip_stream_decompress_data_to_file_iterate(void *data) +{ + struct sevenzip_context_t *sevenzip_context = + (struct sevenzip_context_t*)data; + + SRes res = SZ_ERROR_FAIL; + size_t output_size = 0; + size_t offset = 0; + size_t outSizeProcessed = 0; + + res = SzArEx_Extract(&sevenzip_context->db, + &sevenzip_context->lookStream.s, sevenzip_context->index, + &sevenzip_context->block_index, &sevenzip_context->output, + &output_size, &offset, &outSizeProcessed, + &sevenzip_context->allocImp, &sevenzip_context->allocTempImp); + + if (res != SZ_OK) + return 0; + + if (sevenzip_context->handle) + sevenzip_context->handle->data = sevenzip_context->output + offset; + + return 1; +} + +static int sevenzip_parse_file_init(file_archive_transfer_t *state, + const char *file) +{ + struct sevenzip_context_t *sevenzip_context = + (struct sevenzip_context_t*)sevenzip_stream_new(); + + if (state->archive_size < SEVENZIP_MAGIC_LEN) + goto error; + + if (string_is_not_equal_fast(state->data, SEVENZIP_MAGIC, SEVENZIP_MAGIC_LEN)) + goto error; + + state->stream = sevenzip_context; + + /* could not open 7zip archive? */ + if (InFile_Open(&sevenzip_context->archiveStream.file, file)) + goto error; + + FileInStream_CreateVTable(&sevenzip_context->archiveStream); + LookToRead_CreateVTable(&sevenzip_context->lookStream, false); + sevenzip_context->lookStream.realStream = &sevenzip_context->archiveStream.s; + LookToRead_Init(&sevenzip_context->lookStream); + CrcGenerateTable(); + SzArEx_Init(&sevenzip_context->db); + + if (SzArEx_Open(&sevenzip_context->db, &sevenzip_context->lookStream.s, + &sevenzip_context->allocImp, &sevenzip_context->allocTempImp) != SZ_OK) + goto error; + + return 0; + +error: + if (sevenzip_context) + sevenzip_stream_free(sevenzip_context); + return -1; +} + +static int sevenzip_parse_file_iterate_step_internal( + file_archive_transfer_t *state, char *filename, + const uint8_t **cdata, unsigned *cmode, + uint32_t *size, uint32_t *csize, uint32_t *checksum, + unsigned *payback, struct archive_extract_userdata *userdata) +{ + struct sevenzip_context_t *sevenzip_context = (struct sevenzip_context_t*)state->stream; + const CSzFileItem *file = sevenzip_context->db.db.Files + sevenzip_context->index; + + if (sevenzip_context->index < sevenzip_context->db.db.NumFiles) + { + size_t len = SzArEx_GetFileNameUtf16(&sevenzip_context->db, + sevenzip_context->index, NULL); + uint64_t compressed_size = 0; + + if (sevenzip_context->packIndex < sevenzip_context->db.db.NumPackStreams) + { + compressed_size = sevenzip_context->db.db.PackSizes[sevenzip_context->packIndex]; + sevenzip_context->packIndex++; + } + + if (len < PATH_MAX_LENGTH && !file->IsDir) + { + char infile[PATH_MAX_LENGTH]; + SRes res = SZ_ERROR_FAIL; + uint16_t *temp = (uint16_t*)malloc(len * sizeof(uint16_t)); + + if (!temp) + return -1; + + infile[0] = '\0'; + + SzArEx_GetFileNameUtf16(&sevenzip_context->db, sevenzip_context->index, + temp); + + if (temp) + { + res = utf16_to_char_string(temp, infile, sizeof(infile)) + ? SZ_OK : SZ_ERROR_FAIL; + free(temp); + } + + if (res != SZ_OK) + return -1; + + strlcpy(filename, infile, PATH_MAX_LENGTH); + + *cmode = ARCHIVE_MODE_COMPRESSED; + *checksum = file->Crc; + *size = (uint32_t)file->Size; + *csize = (uint32_t)compressed_size; + } + } + + *payback = 1; + + return 1; +} + +static int sevenzip_parse_file_iterate_step(file_archive_transfer_t *state, + const char *valid_exts, + struct archive_extract_userdata *userdata, file_archive_file_cb file_cb) +{ + char filename[PATH_MAX_LENGTH]; + const uint8_t *cdata = NULL; + uint32_t checksum = 0; + uint32_t size = 0; + uint32_t csize = 0; + unsigned cmode = 0; + unsigned payload = 0; + struct sevenzip_context_t *sevenzip_context = NULL; + int ret; + + filename[0] = '\0'; + + ret = sevenzip_parse_file_iterate_step_internal(state, filename, + &cdata, &cmode, &size, &csize, + &checksum, &payload, userdata); + + if (ret != 1) + return ret; + + userdata->extracted_file_path = filename; + userdata->crc = checksum; + + if (file_cb && !file_cb(filename, valid_exts, cdata, cmode, + csize, size, checksum, userdata)) + return 0; + + sevenzip_context = (struct sevenzip_context_t*)state->stream; + + sevenzip_context->index += payload; + + return 1; +} + +static uint32_t sevenzip_stream_crc32_calculate(uint32_t crc, + const uint8_t *data, size_t length) +{ + return encoding_crc32(crc, data, length); +} + +const struct file_archive_file_backend sevenzip_backend = { + sevenzip_stream_new, + sevenzip_stream_free, + sevenzip_stream_decompress_data_to_file_init, + sevenzip_stream_decompress_data_to_file_iterate, + sevenzip_stream_crc32_calculate, + sevenzip_file_read, + sevenzip_parse_file_init, + sevenzip_parse_file_iterate_step, + "7z" +}; diff --git a/libretro/libretro-common/file/archive_file_zlib.c b/libretro/libretro-common/file/archive_file_zlib.c new file mode 100644 index 0000000..1814ecd --- /dev/null +++ b/libretro/libretro-common/file/archive_file_zlib.c @@ -0,0 +1,391 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (archive_file_zlib.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +/* Only for MAX_WBITS */ +#include + +#ifndef CENTRAL_FILE_HEADER_SIGNATURE +#define CENTRAL_FILE_HEADER_SIGNATURE 0x02014b50 +#endif + +#ifndef END_OF_CENTRAL_DIR_SIGNATURE +#define END_OF_CENTRAL_DIR_SIGNATURE 0x06054b50 +#endif + +static INLINE uint32_t read_le(const uint8_t *data, unsigned size) +{ + unsigned i; + uint32_t val = 0; + + size *= 8; + for (i = 0; i < size; i += 8) + val |= (uint32_t)*data++ << i; + + return val; +} + +static void *zlib_stream_new(void) +{ + return zlib_inflate_backend.stream_new(); +} + +static void zlib_stream_free(void *stream) +{ + zlib_inflate_backend.stream_free(stream); +} + +static bool zlib_stream_decompress_data_to_file_init( + file_archive_file_handle_t *handle, + const uint8_t *cdata, uint32_t csize, uint32_t size) +{ + if (!handle) + return false; + + handle->stream = zlib_inflate_backend.stream_new(); + + if (!handle->stream) + goto error; + + if (zlib_inflate_backend.define) + zlib_inflate_backend.define(handle->stream, "window_bits", (uint32_t)-MAX_WBITS); + + handle->data = (uint8_t*)malloc(size); + + if (!handle->data) + goto error; + + zlib_inflate_backend.set_in(handle->stream, + (const uint8_t*)cdata, csize); + zlib_inflate_backend.set_out(handle->stream, + handle->data, size); + + return true; + +error: + if (handle->stream) + zlib_inflate_backend.stream_free(handle->stream); + if (handle->data) + free(handle->data); + + return false; +} + +static int zlib_stream_decompress_data_to_file_iterate(void *stream) +{ + bool zstatus; + uint32_t rd, wn; + enum trans_stream_error terror; + + if (!stream) + return -1; + + zstatus = zlib_inflate_backend.trans(stream, false, &rd, &wn, &terror); + + if (!zstatus && terror != TRANS_STREAM_ERROR_BUFFER_FULL) + return -1; + + if (zstatus && !terror) + return 1; + + return 0; +} + +static uint32_t zlib_stream_crc32_calculate(uint32_t crc, + const uint8_t *data, size_t length) +{ + return encoding_crc32(crc, data, length); +} + +static bool zip_file_decompressed_handle( + file_archive_file_handle_t *handle, + const uint8_t *cdata, uint32_t csize, + uint32_t size, uint32_t crc32) +{ + int ret = 0; + + handle->backend = &zlib_backend; + + if (!handle->backend->stream_decompress_data_to_file_init( + handle, cdata, csize, size)) + return false; + + do + { + ret = handle->backend->stream_decompress_data_to_file_iterate( + handle->stream); + }while(ret == 0); + +#if 0 + handle->real_checksum = handle->backend->stream_crc_calculate(0, + handle->data, size); + + if (handle->real_checksum != crc32) + goto error; +#endif + + if (handle->stream) + free(handle->stream); + + return true; +#if 0 +error: + if (handle->stream) + free(handle->stream); + if (handle->data) + free(handle->data); + + handle->stream = NULL; + handle->data = NULL; + return false; +#endif +} + +/* Extract the relative path (needle) from a + * ZIP archive (path) and allocate a buffer for it to write it in. + * + * optional_outfile if not NULL will be used to extract the file to. + * buf will be 0 then. + */ + +static int zip_file_decompressed( + const char *name, const char *valid_exts, + const uint8_t *cdata, unsigned cmode, + uint32_t csize, uint32_t size, + uint32_t crc32, struct archive_extract_userdata *userdata) +{ + /* Ignore directories. */ + if (name[strlen(name) - 1] == '/' || name[strlen(name) - 1] == '\\') + return 1; + +#if 0 + RARCH_LOG("[deflate] Path: %s, CRC32: 0x%x\n", name, crc32); +#endif + + if (strstr(name, userdata->decomp_state.needle)) + { + bool goto_error = false; + file_archive_file_handle_t handle = {0}; + + userdata->decomp_state.found = true; + + if (zip_file_decompressed_handle(&handle, + cdata, csize, size, crc32)) + { + if (userdata->decomp_state.opt_file != 0) + { + /* Called in case core has need_fullpath enabled. */ + char *buf = (char*)malloc(size); + + if (buf) + { + /*RARCH_LOG("%s: %s\n", + msg_hash_to_str(MSG_EXTRACTING_FILE), + userdata->decomp_state.opt_file);*/ + memcpy(buf, handle.data, size); + + if (!filestream_write_file(userdata->decomp_state.opt_file, buf, size)) + goto_error = true; + } + + free(buf); + + userdata->decomp_state.size = 0; + } + else + { + /* Called in case core has need_fullpath disabled. + * Will copy decompressed content directly into + * RetroArch's ROM buffer. */ + *userdata->decomp_state.buf = malloc(size); + memcpy(*userdata->decomp_state.buf, handle.data, size); + + userdata->decomp_state.size = size; + } + } + + if (handle.data) + free(handle.data); + + if (goto_error) + return 0; + } + + return 1; +} + +static int zip_file_read( + const char *path, + const char *needle, void **buf, + const char *optional_outfile) +{ + file_archive_transfer_t zlib; + struct archive_extract_userdata userdata = {{0}}; + bool returnerr = true; + int ret = 0; + + zlib.type = ARCHIVE_TRANSFER_INIT; + + userdata.decomp_state.needle = NULL; + userdata.decomp_state.opt_file = NULL; + userdata.decomp_state.found = false; + userdata.decomp_state.buf = buf; + + if (needle) + userdata.decomp_state.needle = strdup(needle); + if (optional_outfile) + userdata.decomp_state.opt_file = strdup(optional_outfile); + + do + { + ret = file_archive_parse_file_iterate(&zlib, &returnerr, path, + "", zip_file_decompressed, &userdata); + if (!returnerr) + break; + }while(ret == 0 && !userdata.decomp_state.found); + + file_archive_parse_file_iterate_stop(&zlib); + + if (userdata.decomp_state.opt_file) + free(userdata.decomp_state.opt_file); + if (userdata.decomp_state.needle) + free(userdata.decomp_state.needle); + + if (!userdata.decomp_state.found) + return -1; + + return (int)userdata.decomp_state.size; +} + +static int zip_parse_file_init(file_archive_transfer_t *state, + const char *file) +{ + if (state->archive_size < 22) + return -1; + + state->footer = state->data + state->archive_size - 22; + + for (;; state->footer--) + { + if (state->footer <= state->data + 22) + return -1; + if (read_le(state->footer, 4) == END_OF_CENTRAL_DIR_SIGNATURE) + { + unsigned comment_len = read_le(state->footer + 20, 2); + if (state->footer + 22 + comment_len == state->data + state->archive_size) + break; + } + } + + state->directory = state->data + read_le(state->footer + 16, 4); + + return 0; +} + +static int zip_parse_file_iterate_step_internal( + file_archive_transfer_t *state, char *filename, + const uint8_t **cdata, + unsigned *cmode, uint32_t *size, uint32_t *csize, + uint32_t *checksum, unsigned *payback) +{ + uint32_t offset; + uint32_t namelength, extralength, commentlength, + offsetNL, offsetEL; + uint32_t signature = read_le(state->directory + 0, 4); + + if (signature != CENTRAL_FILE_HEADER_SIGNATURE) + return 0; + + *cmode = read_le(state->directory + 10, 2); /* compression mode, 0 = store, 8 = deflate */ + *checksum = read_le(state->directory + 16, 4); /* CRC32 */ + *csize = read_le(state->directory + 20, 4); /* compressed size */ + *size = read_le(state->directory + 24, 4); /* uncompressed size */ + + namelength = read_le(state->directory + 28, 2); /* file name length */ + extralength = read_le(state->directory + 30, 2); /* extra field length */ + commentlength = read_le(state->directory + 32, 2); /* file comment length */ + + if (namelength >= PATH_MAX_LENGTH) + return -1; + + memcpy(filename, state->directory + 46, namelength); /* file name */ + + offset = read_le(state->directory + 42, 4); /* relative offset of local file header */ + offsetNL = read_le(state->data + offset + 26, 2); /* file name length */ + offsetEL = read_le(state->data + offset + 28, 2); /* extra field length */ + + *cdata = state->data + offset + 30 + offsetNL + offsetEL; + + *payback = 46 + namelength + extralength + commentlength; + + return 1; +} + +static int zip_parse_file_iterate_step(file_archive_transfer_t *state, + const char *valid_exts, struct archive_extract_userdata *userdata, + file_archive_file_cb file_cb) +{ + char filename[PATH_MAX_LENGTH] = {0}; + const uint8_t *cdata = NULL; + uint32_t checksum = 0; + uint32_t size = 0; + uint32_t csize = 0; + unsigned cmode = 0; + unsigned payload = 0; + int ret = zip_parse_file_iterate_step_internal( + state, filename, &cdata, &cmode, &size, &csize, &checksum, &payload); + + if (ret != 1) + return ret; + + userdata->extracted_file_path = filename; + userdata->crc = checksum; + + if (file_cb && !file_cb(filename, valid_exts, cdata, cmode, + csize, size, checksum, userdata)) + return 0; + + state->directory += payload; + + return 1; +} + +const struct file_archive_file_backend zlib_backend = { + zlib_stream_new, + zlib_stream_free, + zlib_stream_decompress_data_to_file_init, + zlib_stream_decompress_data_to_file_iterate, + zlib_stream_crc32_calculate, + zip_file_read, + zip_parse_file_init, + zip_parse_file_iterate_step, + "zlib" +}; diff --git a/libretro/libretro-common/file/config_file.c b/libretro/libretro-common/file/config_file.c new file mode 100644 index 0000000..18259e3 --- /dev/null +++ b/libretro/libretro-common/file/config_file.c @@ -0,0 +1,996 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (config_file.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include +#include +#include + +#if !defined(_WIN32) && !defined(__CELLOS_LV2__) && !defined(_XBOX) +#include /* PATH_MAX */ +#elif defined(_WIN32) && !defined(_XBOX) +#define WIN32_LEAN_AND_MEAN +#include +#elif defined(_XBOX) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_INCLUDE_DEPTH 16 + +struct config_entry_list +{ + /* If we got this from an #include, + * do not allow overwrite. */ + bool readonly; + uint32_t key_hash; + + char *key; + char *value; + struct config_entry_list *next; +}; + +struct config_include_list +{ + char *path; + struct config_include_list *next; +}; + +struct config_file +{ + char *path; + struct config_entry_list *entries; + struct config_entry_list *tail; + unsigned include_depth; + + struct config_include_list *includes; +}; + +static config_file_t *config_file_new_internal( + const char *path, unsigned depth); + +static char *getaline(FILE *file) +{ + char* newline = (char*)malloc(9); + char* newline_tmp = NULL; + size_t cur_size = 8; + size_t idx = 0; + int in = getc(file); + + if (!newline) + return NULL; + + while (in != EOF && in != '\n') + { + if (idx == cur_size) + { + cur_size *= 2; + newline_tmp = (char*)realloc(newline, cur_size + 1); + + if (!newline_tmp) + { + free(newline); + return NULL; + } + + newline = newline_tmp; + } + + newline[idx++] = in; + in = getc(file); + } + newline[idx] = '\0'; + return newline; +} + +static char *strip_comment(char *str) +{ + /* Remove everything after comment. + * Keep #s inside string literals. */ + char *string_end = str + strlen(str); + bool cut_comment = true; + + while (!string_is_empty(str)) + { + char *comment = NULL; + char *literal = strchr(str, '\"'); + if (!literal) + literal = string_end; + comment = (char*)strchr(str, '#'); + + if (!comment) + comment = string_end; + + if (cut_comment && literal < comment) + { + cut_comment = false; + str = literal + 1; + } + else if (!cut_comment && literal) + { + cut_comment = true; + str = literal + 1; + } + else + { + *comment = '\0'; + str = comment; + } + } + + return str; +} + +static char *extract_value(char *line, bool is_value) +{ + char *save = NULL; + char *tok = NULL; + + if (is_value) + { + while (isspace((int)*line)) + line++; + + /* If we don't have an equal sign here, + * we've got an invalid string. */ + if (*line != '=') + return NULL; + + line++; + } + + while (isspace((int)*line)) + line++; + + /* We have a full string. Read until next ". */ + if (*line == '"') + { + line++; + tok = strtok_r(line, "\"", &save); + if (!tok) + return NULL; + return strdup(tok); + } + else if (*line == '\0') /* Nothing */ + return NULL; + + /* We don't have that. Read until next space. */ + tok = strtok_r(line, " \n\t\f\r\v", &save); + if (tok) + return strdup(tok); + return NULL; +} + +/* Move semantics? */ +static void add_child_list(config_file_t *parent, config_file_t *child) +{ + struct config_entry_list *list = child->entries; + if (parent->entries) + { + struct config_entry_list *head = parent->entries; + while (head->next) + head = head->next; + + /* set list readonly */ + while (list) + { + list->readonly = true; + list = list->next; + } + head->next = child->entries; + } + else + { + /* set list readonly */ + while (list) + { + list->readonly = true; + list = list->next; + } + parent->entries = child->entries; + } + + child->entries = NULL; + + /* Rebase tail. */ + if (parent->entries) + { + struct config_entry_list *head = + (struct config_entry_list*)parent->entries; + + while (head->next) + head = head->next; + parent->tail = head; + } + else + parent->tail = NULL; +} + +static void add_sub_conf(config_file_t *conf, char *path) +{ + char real_path[PATH_MAX_LENGTH]; + config_file_t *sub_conf = NULL; + struct config_include_list *head = conf->includes; + struct config_include_list *node = (struct config_include_list*)malloc(sizeof(*node)); + + if (node) + { + node->next = NULL; + /* Add include list */ + node->path = strdup(path); + + if (head) + { + while (head->next) + head = head->next; + + head->next = node; + } + else + conf->includes = node; + } + + real_path[0] = '\0'; + +#ifdef _WIN32 + if (!string_is_empty(conf->path)) + fill_pathname_resolve_relative(real_path, conf->path, + path, sizeof(real_path)); +#else +#ifndef __CELLOS_LV2__ + if (*path == '~') + { + const char *home = getenv("HOME"); + strlcpy(real_path, home ? home : "", sizeof(real_path)); + strlcat(real_path, path + 1, sizeof(real_path)); + } + else +#endif + if (!string_is_empty(conf->path)) + fill_pathname_resolve_relative(real_path, conf->path, + path, sizeof(real_path)); +#endif + + sub_conf = (config_file_t*) + config_file_new_internal(real_path, conf->include_depth + 1); + if (!sub_conf) + { + free(path); + return; + } + + /* Pilfer internal list. */ + add_child_list(conf, sub_conf); + config_file_free(sub_conf); + free(path); +} + +static bool parse_line(config_file_t *conf, + struct config_entry_list *list, char *line) +{ + char *comment = NULL; + char *key_tmp = NULL; + size_t cur_size = 8; + size_t idx = 0; + char *key = (char*)malloc(9); + + if (!key) + return false; + + comment = strip_comment(line); + + /* Starting line with # and include includes config files. */ + if ((comment == line) && (conf->include_depth < MAX_INCLUDE_DEPTH)) + { + comment++; + if (strstr(comment, "include ") == comment) + { + char *line = comment + strlen("include "); + char *path = extract_value(line, false); + if (path) + add_sub_conf(conf, path); + goto error; + } + } + else if (conf->include_depth >= MAX_INCLUDE_DEPTH) + { + fprintf(stderr, "!!! #include depth exceeded for config. Might be a cycle.\n"); + } + + /* Skips to first character. */ + while (isspace((int)*line)) + line++; + + while (isgraph((int)*line)) + { + if (idx == cur_size) + { + cur_size *= 2; + key_tmp = (char*)realloc(key, cur_size + 1); + + if (!key_tmp) + goto error; + + key = key_tmp; + } + + key[idx++] = *line++; + } + key[idx] = '\0'; + list->key = key; + list->key_hash = djb2_calculate(key); + + list->value = extract_value(line, true); + if (!list->value) + { + list->key = NULL; + goto error; + } + + return true; + +error: + free(key); + return false; +} + +static config_file_t *config_file_new_internal( + const char *path, unsigned depth) +{ + FILE *file = NULL; + struct config_file *conf = (struct config_file*)malloc(sizeof(*conf)); + if (!conf) + return NULL; + + conf->path = NULL; + conf->entries = NULL; + conf->tail = NULL; + conf->includes = NULL; + conf->include_depth = 0; + + if (!path || !*path) + return conf; + + if (path_is_directory(path)) + goto error; + + conf->path = strdup(path); + if (!conf->path) + goto error; + + conf->include_depth = depth; + file = fopen(path, "r"); + + if (!file) + { + free(conf->path); + goto error; + } + setvbuf(file, NULL, _IOFBF, 0x4000); + + while (!feof(file)) + { + char *line = NULL; + struct config_entry_list *list = (struct config_entry_list*)malloc(sizeof(*list)); + + if (!list) + { + config_file_free(conf); + fclose(file); + return NULL; + } + + list->readonly = false; + list->key_hash = 0; + list->key = NULL; + list->value = NULL; + list->next = NULL; + + line = getaline(file); + + if (!line) + { + free(list); + continue; + } + + if (*line && parse_line(conf, list, line)) + { + if (conf->entries) + conf->tail->next = list; + else + conf->entries = list; + + conf->tail = list; + } + + free(line); + + if (list != conf->tail) + free(list); + } + + fclose(file); + + return conf; + +error: + free(conf); + + return NULL; +} + +void config_file_free(config_file_t *conf) +{ + struct config_include_list *inc_tmp = NULL; + struct config_entry_list *tmp = NULL; + if (!conf) + return; + + tmp = conf->entries; + while (tmp) + { + struct config_entry_list *hold = NULL; + if (tmp->key) + free(tmp->key); + if (tmp->value) + free(tmp->value); + + tmp->value = NULL; + tmp->key = NULL; + + hold = tmp; + tmp = tmp->next; + + if (hold) + free(hold); + } + + inc_tmp = (struct config_include_list*)conf->includes; + while (inc_tmp) + { + struct config_include_list *hold = NULL; + free(inc_tmp->path); + hold = (struct config_include_list*)inc_tmp; + inc_tmp = inc_tmp->next; + free(hold); + } + + if (conf->path) + free(conf->path); + free(conf); +} + +bool config_append_file(config_file_t *conf, const char *path) +{ + config_file_t *new_conf = config_file_new(path); + if (!new_conf) + return false; + + if (new_conf->tail) + { + new_conf->tail->next = conf->entries; + conf->entries = new_conf->entries; /* Pilfer. */ + new_conf->entries = NULL; + } + + config_file_free(new_conf); + return true; +} + + +config_file_t *config_file_new_from_string(const char *from_string) +{ + size_t i; + struct string_list *lines = NULL; + struct config_file *conf = (struct config_file*)malloc(sizeof(*conf)); + if (!conf) + return NULL; + + if (!from_string) + return conf; + + conf->path = NULL; + conf->entries = NULL; + conf->tail = NULL; + conf->includes = NULL; + conf->include_depth = 0; + + lines = string_split(from_string, "\n"); + if (!lines) + return conf; + + for (i = 0; i < lines->size; i++) + { + struct config_entry_list *list = (struct config_entry_list*)malloc(sizeof(*list)); + char *line = lines->elems[i].data; + + if (!list) + { + string_list_free(lines); + config_file_free(conf); + return NULL; + } + + list->readonly = false; + list->key_hash = 0; + list->key = NULL; + list->value = NULL; + list->next = NULL; + + if (line && conf) + { + if (*line && parse_line(conf, list, line)) + { + if (conf->entries) + conf->tail->next = list; + else + conf->entries = list; + + conf->tail = list; + } + } + + if (list != conf->tail) + free(list); + } + + string_list_free(lines); + + return conf; +} + +config_file_t *config_file_new(const char *path) +{ + return config_file_new_internal(path, 0); +} + + +static struct config_entry_list *config_get_entry(const config_file_t *conf, + const char *key, struct config_entry_list **prev) +{ + struct config_entry_list *entry; + struct config_entry_list *previous = NULL; + + uint32_t hash = djb2_calculate(key); + + if (prev) + previous = *prev; + + for (entry = conf->entries; entry; entry = entry->next) + { + if (hash == entry->key_hash && string_is_equal(key, entry->key)) + return entry; + + previous = entry; + } + + if (prev) + *prev = previous; + + return NULL; +} + +bool config_get_double(config_file_t *conf, const char *key, double *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + *in = strtod(entry->value, NULL); + + return entry != NULL; +} + +bool config_get_float(config_file_t *conf, const char *key, float *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + { + /* strtof() is C99/POSIX. Just use the more portable kind. */ + *in = (float)strtod(entry->value, NULL); + } + + return entry != NULL; +} + +bool config_get_int(config_file_t *conf, const char *key, int *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + errno = 0; + + if (entry) + { + int val = (int)strtol(entry->value, NULL, 0); + + if (errno == 0) + *in = val; + } + + return entry != NULL && errno == 0; +} + +#if defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L +bool config_get_uint64(config_file_t *conf, const char *key, uint64_t *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + errno = 0; + + if (entry) + { + uint64_t val = strtoull(entry->value, NULL, 0); + + if (errno == 0) + *in = val; + } + + return entry != NULL && errno == 0; +} +#endif + +bool config_get_uint(config_file_t *conf, const char *key, unsigned *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + errno = 0; + + if (entry) + { + unsigned val = (unsigned)strtoul(entry->value, NULL, 0); + + if (errno == 0) + *in = val; + } + + return entry != NULL && errno == 0; +} + +bool config_get_hex(config_file_t *conf, const char *key, unsigned *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + errno = 0; + + if (entry) + { + unsigned val = (unsigned)strtoul(entry->value, NULL, 16); + + if (errno == 0) + *in = val; + } + + return entry != NULL && errno == 0; +} + +bool config_get_char(config_file_t *conf, const char *key, char *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + { + if (entry->value[0] && entry->value[1]) + return false; + + *in = *entry->value; + } + + return entry != NULL; +} + +bool config_get_string(config_file_t *conf, const char *key, char **str) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + *str = strdup(entry->value); + + return entry != NULL; +} + +bool config_get_config_path(config_file_t *conf, char *s, size_t len) +{ + if (!conf) + return false; + + return strlcpy(s, conf->path, len); +} + +bool config_get_array(config_file_t *conf, const char *key, + char *buf, size_t size) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + return strlcpy(buf, entry->value, size) < size; + + return entry != NULL; +} + +bool config_get_path(config_file_t *conf, const char *key, + char *buf, size_t size) +{ +#if defined(RARCH_CONSOLE) + return config_get_array(conf, key, buf, size); +#else + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + fill_pathname_expand_special(buf, entry->value, size); + + return entry != NULL; +#endif +} + +bool config_get_bool(config_file_t *conf, const char *key, bool *in) +{ + const struct config_entry_list *entry = config_get_entry(conf, key, NULL); + + if (entry) + { + if (string_is_equal_fast(entry->value, "true", 4)) + *in = true; + else if (string_is_equal_fast(entry->value, "1", 1)) + *in = true; + else if (string_is_equal_fast(entry->value, "false", 5)) + *in = false; + else if (string_is_equal_fast(entry->value, "0", 1)) + *in = false; + else + return false; + } + + return entry != NULL; +} + +void config_set_string(config_file_t *conf, const char *key, const char *val) +{ + struct config_entry_list *last = conf->entries; + struct config_entry_list *entry = config_get_entry(conf, key, &last); + + if (entry && !entry->readonly) + { + free(entry->value); + entry->value = strdup(val); + return; + } + + if (!val) + return; + + entry = (struct config_entry_list*)malloc(sizeof(*entry)); + if (!entry) + return; + + entry->readonly = false; + entry->key_hash = 0; + entry->key = strdup(key); + entry->value = strdup(val); + entry->next = NULL; + + if (last) + last->next = entry; + else + conf->entries = entry; +} + +void config_unset(config_file_t *conf, const char *key) +{ + struct config_entry_list *last = conf->entries; + struct config_entry_list *entry = config_get_entry(conf, key, &last); + + if (!entry) + return; + + entry->key = NULL; + entry->value = NULL; + free(entry->key); + free(entry->value); +} + +void config_set_path(config_file_t *conf, const char *entry, const char *val) +{ +#if defined(RARCH_CONSOLE) + config_set_string(conf, entry, val); +#else + char buf[PATH_MAX_LENGTH]; + + buf[0] = '\0'; + fill_pathname_abbreviate_special(buf, val, sizeof(buf)); + config_set_string(conf, entry, buf); +#endif +} + +void config_set_double(config_file_t *conf, const char *key, double val) +{ + char buf[128]; + + buf[0] = '\0'; +#ifdef __cplusplus + snprintf(buf, sizeof(buf), "%f", (float)val); +#elif defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L + snprintf(buf, sizeof(buf), "%lf", val); +#else + snprintf(buf, sizeof(buf), "%f", (float)val); +#endif + config_set_string(conf, key, buf); +} + +void config_set_float(config_file_t *conf, const char *key, float val) +{ + char buf[128]; + + buf[0] = '\0'; + snprintf(buf, sizeof(buf), "%f", val); + config_set_string(conf, key, buf); +} + +void config_set_int(config_file_t *conf, const char *key, int val) +{ + char buf[128]; + + buf[0] = '\0'; + snprintf(buf, sizeof(buf), "%d", val); + config_set_string(conf, key, buf); +} + +void config_set_hex(config_file_t *conf, const char *key, unsigned val) +{ + char buf[128]; + + buf[0] = '\0'; + snprintf(buf, sizeof(buf), "%x", val); + config_set_string(conf, key, buf); +} + +void config_set_uint64(config_file_t *conf, const char *key, uint64_t val) +{ + char buf[128]; + + buf[0] = '\0'; +#ifdef _WIN32 + snprintf(buf, sizeof(buf), "%I64u", val); +#else + snprintf(buf, sizeof(buf), "%llu", (long long unsigned)val); +#endif + config_set_string(conf, key, buf); +} + +void config_set_char(config_file_t *conf, const char *key, char val) +{ + char buf[2]; + + buf[0] = '\0'; + snprintf(buf, sizeof(buf), "%c", val); + config_set_string(conf, key, buf); +} + +void config_set_bool(config_file_t *conf, const char *key, bool val) +{ + config_set_string(conf, key, val ? "true" : "false"); +} + +bool config_file_write(config_file_t *conf, const char *path) +{ + FILE *file; + + if (path && !string_is_empty(path)) + { + file = fopen(path, "w"); + if (!file) + return false; +#ifdef WIIU + /* TODO: use FBF everywhere once https://i.imgur.com/muVhNeF.jpg is fixed */ + setvbuf(file, NULL, _IONBF, 0x4000); +#else + setvbuf(file, NULL, _IOFBF, 0x4000); +#endif + } + else + file = stdout; + + config_file_dump(conf, file); + + if (path) + fclose(file); + + return true; +} + +void config_file_dump(config_file_t *conf, FILE *file) +{ + struct config_entry_list *list = NULL; + struct config_include_list *includes = conf->includes; + + while (includes) + { + fprintf(file, "#include \"%s\"\n", includes->path); + includes = includes->next; + } + + list = (struct config_entry_list*)conf->entries; + + while (list) + { + if (!list->readonly && list->key) + fprintf(file, "%s = \"%s\"\n", list->key, list->value); + list = list->next; + } +} + +bool config_entry_exists(config_file_t *conf, const char *entry) +{ + struct config_entry_list *list = conf->entries; + + while (list) + { + if (string_is_equal(entry, list->key)) + return true; + list = list->next; + } + + return false; +} + +bool config_get_entry_list_head(config_file_t *conf, + struct config_file_entry *entry) +{ + const struct config_entry_list *head = conf->entries; + + if (!head) + return false; + + entry->key = head->key; + entry->value = head->value; + entry->next = head->next; + return true; +} + +bool config_get_entry_list_next(struct config_file_entry *entry) +{ + const struct config_entry_list *next = entry->next; + + if (!next) + return false; + + entry->key = next->key; + entry->value = next->value; + entry->next = next->next; + return true; +} + +bool config_file_exists(const char *path) +{ + config_file_t *config = config_file_new(path); + if (!config) + return false; + + config_file_free(config); + return true; +} diff --git a/libretro/libretro-common/file/config_file_userdata.c b/libretro/libretro-common/file/config_file_userdata.c new file mode 100644 index 0000000..022715a --- /dev/null +++ b/libretro/libretro-common/file/config_file_userdata.c @@ -0,0 +1,149 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (config_file_userdata.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include + +#include + +int config_userdata_get_float(void *userdata, const char *key_str, + float *value, float default_value) +{ + bool got; + char key[2][256]; + struct config_file_userdata *usr = (struct config_file_userdata*)userdata; + + fill_pathname_join_delim(key[0], usr->prefix[0], key_str, '_', sizeof(key[0])); + fill_pathname_join_delim(key[1], usr->prefix[1], key_str, '_', sizeof(key[1])); + + got = config_get_float (usr->conf, key[0], value); + got = got || config_get_float(usr->conf, key[1], value); + + if (!got) + *value = default_value; + return got; +} + +int config_userdata_get_int(void *userdata, const char *key_str, + int *value, int default_value) +{ + bool got; + char key[2][256]; + struct config_file_userdata *usr = (struct config_file_userdata*)userdata; + + fill_pathname_join_delim(key[0], usr->prefix[0], key_str, '_', sizeof(key[0])); + fill_pathname_join_delim(key[1], usr->prefix[1], key_str, '_', sizeof(key[1])); + + got = config_get_int (usr->conf, key[0], value); + got = got || config_get_int(usr->conf, key[1], value); + + if (!got) + *value = default_value; + return got; +} + +int config_userdata_get_float_array(void *userdata, const char *key_str, + float **values, unsigned *out_num_values, + const float *default_values, unsigned num_default_values) +{ + char key[2][256]; + struct config_file_userdata *usr = (struct config_file_userdata*)userdata; + char *str = NULL; + + fill_pathname_join_delim(key[0], usr->prefix[0], key_str, '_', sizeof(key[0])); + fill_pathname_join_delim(key[1], usr->prefix[1], key_str, '_', sizeof(key[1])); + + if ( config_get_string(usr->conf, key[0], &str) || + config_get_string(usr->conf, key[1], &str)) + { + unsigned i; + struct string_list *list = string_split(str, " "); + *values = (float*)calloc(list->size, sizeof(float)); + for (i = 0; i < list->size; i++) + (*values)[i] = (float)strtod(list->elems[i].data, NULL); + *out_num_values = (unsigned)list->size; + string_list_free(list); + free(str); + return true; + } + + *values = (float*)calloc(num_default_values, sizeof(float)); + memcpy(*values, default_values, sizeof(float) * num_default_values); + *out_num_values = num_default_values; + return false; +} + +int config_userdata_get_int_array(void *userdata, const char *key_str, + int **values, unsigned *out_num_values, + const int *default_values, unsigned num_default_values) +{ + char key[2][256]; + struct config_file_userdata *usr = (struct config_file_userdata*)userdata; + char *str = NULL; + fill_pathname_join_delim(key[0], usr->prefix[0], key_str, '_', sizeof(key[0])); + fill_pathname_join_delim(key[1], usr->prefix[1], key_str, '_', sizeof(key[1])); + + if ( config_get_string(usr->conf, key[0], &str) || + config_get_string(usr->conf, key[1], &str)) + { + unsigned i; + struct string_list *list = string_split(str, " "); + *values = (int*)calloc(list->size, sizeof(int)); + for (i = 0; i < list->size; i++) + (*values)[i] = (int)strtod(list->elems[i].data, NULL); + *out_num_values = (unsigned)list->size; + string_list_free(list); + free(str); + return true; + } + + *values = (int*)calloc(num_default_values, sizeof(int)); + memcpy(*values, default_values, sizeof(int) * num_default_values); + *out_num_values = num_default_values; + return false; +} + +int config_userdata_get_string(void *userdata, const char *key_str, + char **output, const char *default_output) +{ + char key[2][256]; + struct config_file_userdata *usr = (struct config_file_userdata*)userdata; + char *str = NULL; + fill_pathname_join_delim(key[0], usr->prefix[0], key_str, '_', sizeof(key[0])); + fill_pathname_join_delim(key[1], usr->prefix[1], key_str, '_', sizeof(key[1])); + + if ( config_get_string(usr->conf, key[0], &str) || + config_get_string(usr->conf, key[1], &str)) + { + *output = str; + return true; + } + + *output = strdup(default_output); + return false; +} + +void config_userdata_free(void *ptr) +{ + if (ptr) + free(ptr); +} diff --git a/libretro/libretro-common/file/file_path.c b/libretro/libretro-common/file/file_path.c new file mode 100644 index 0000000..2740397 --- /dev/null +++ b/libretro/libretro-common/file/file_path.c @@ -0,0 +1,886 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (file_path.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include +#include +#include + +#include + +#include +#include + +#ifndef __MACH__ +#include +#include +#endif +#include +#include + +#if defined(_WIN32) +#ifdef _MSC_VER +#define setmode _setmode +#endif +#include +#ifdef _XBOX +#include +#define INVALID_FILE_ATTRIBUTES -1 +#else +#include +#include +#include +#include +#if defined(_MSC_VER) && _MSC_VER <= 1200 +#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) +#endif +#endif +#elif defined(VITA) +#define SCE_ERROR_ERRNO_EEXIST 0x80010011 +#include +#include +#include +#else +#include +#include +#include +#endif + +#if defined(PSP) +#include +#endif + +#ifdef __HAIKU__ +#include +#endif + +#if defined(__CELLOS_LV2__) +#include +#endif + +#if defined(VITA) +#define FIO_S_ISDIR SCE_S_ISDIR +#endif + +#if (defined(__CELLOS_LV2__) && !defined(__PSL1GHT__)) || defined(__QNX__) || defined(PSP) +#include /* stat() is defined here */ +#endif + +enum stat_mode +{ + IS_DIRECTORY = 0, + IS_CHARACTER_SPECIAL, + IS_VALID +}; + +static bool path_stat(const char *path, enum stat_mode mode, int32_t *size) +{ +#if defined(VITA) || defined(PSP) + SceIoStat buf; + char *tmp = strdup(path); + size_t len = strlen(tmp); + if (tmp[len-1] == '/') + tmp[len-1]='\0'; + + if (sceIoGetstat(tmp, &buf) < 0) + { + free(tmp); + return false; + } + free(tmp); + +#elif defined(__CELLOS_LV2__) + CellFsStat buf; + if (cellFsStat(path, &buf) < 0) + return false; +#elif defined(_WIN32) + struct _stat buf; + DWORD file_info = GetFileAttributes(path); + + _stat(path, &buf); + + if (file_info == INVALID_FILE_ATTRIBUTES) + return false; +#else + struct stat buf; + if (stat(path, &buf) < 0) + return false; +#endif + + if (size) + *size = (int32_t)buf.st_size; + + switch (mode) + { + case IS_DIRECTORY: +#if defined(VITA) || defined(PSP) + return FIO_S_ISDIR(buf.st_mode); +#elif defined(__CELLOS_LV2__) + return ((buf.st_mode & S_IFMT) == S_IFDIR); +#elif defined(_WIN32) + return (file_info & FILE_ATTRIBUTE_DIRECTORY); +#else + return S_ISDIR(buf.st_mode); +#endif + case IS_CHARACTER_SPECIAL: +#if defined(VITA) || defined(PSP) || defined(__CELLOS_LV2__) || defined(_WIN32) + return false; +#else + return S_ISCHR(buf.st_mode); +#endif + case IS_VALID: + return true; + } + + return false; +} + +/** + * path_is_directory: + * @path : path + * + * Checks if path is a directory. + * + * Returns: true (1) if path is a directory, otherwise false (0). + */ +bool path_is_directory(const char *path) +{ + return path_stat(path, IS_DIRECTORY, NULL); +} + +bool path_is_character_special(const char *path) +{ + return path_stat(path, IS_CHARACTER_SPECIAL, NULL); +} + +bool path_is_valid(const char *path) +{ + return path_stat(path, IS_VALID, NULL); +} + +int32_t path_get_size(const char *path) +{ + int32_t filesize = 0; + if (path_stat(path, IS_VALID, &filesize)) + return filesize; + + return -1; +} + +/** + * path_mkdir: + * @dir : directory + * + * Create directory on filesystem. + * + * Returns: true (1) if directory could be created, otherwise false (0). + **/ +bool path_mkdir(const char *dir) +{ + /* Use heap. Real chance of stack overflow if we recurse too hard. */ + char *basedir = strdup(dir); + const char *target = NULL; + bool sret = false; + bool norecurse = false; + + if (!basedir) + return false; + + path_parent_dir(basedir); + if (!*basedir || !strcmp(basedir, dir)) + goto end; + + if (path_is_directory(basedir)) + { + target = dir; + norecurse = true; + } + else + { + target = basedir; + sret = path_mkdir(basedir); + + if (sret) + { + target = dir; + norecurse = true; + } + } + + if (norecurse) + { +#if defined(_WIN32) + int ret = _mkdir(dir); +#elif defined(IOS) + int ret = mkdir(dir, 0755); +#elif defined(VITA) || defined(PSP) + int ret = sceIoMkdir(dir, 0777); +#elif defined(__QNX__) + int ret = mkdir(dir, 0777); +#else + int ret = mkdir(dir, 0750); +#endif + + /* Don't treat this as an error. */ +#if defined(VITA) + if ((ret == SCE_ERROR_ERRNO_EEXIST) && path_is_directory(dir)) + ret = 0; +#elif defined(PSP) || defined(_3DS) || defined(WIIU) + if ((ret == -1) && path_is_directory(dir)) + ret = 0; +#else + if (ret < 0 && errno == EEXIST && path_is_directory(dir)) + ret = 0; +#endif + if (ret < 0) + printf("mkdir(%s) error: %s.\n", dir, strerror(errno)); + sret = (ret == 0); + } + +end: + if (target && !sret) + printf("Failed to create directory: \"%s\".\n", target); + free(basedir); + return sret; +} + +/** + * path_get_archive_delim: + * @path : path + * + * Find delimiter of an archive file. Only the first '#' + * after a compression extension is considered. + * + * Returns: pointer to the delimiter in the path if it contains + * a path inside a compressed file, otherwise NULL. + */ +const char *path_get_archive_delim(const char *path) +{ + const char *last = find_last_slash(path); + const char *delim = NULL; + + if (last) + { + delim = strcasestr(last, ".zip#"); + + if (!delim) + delim = strcasestr(last, ".apk#"); + } + + if (delim) + return delim + 4; + + if (last) + delim = strcasestr(last, ".7z#"); + + if (delim) + return delim + 3; + + return NULL; +} + +/** + * path_get_extension: + * @path : path + * + * Gets extension of file. Only '.'s + * after the last slash are considered. + * + * Returns: extension part from the path. + */ +const char *path_get_extension(const char *path) +{ + const char *ext = strrchr(path_basename(path), '.'); + if (!ext) + return ""; + return ext + 1; +} + +/** + * path_remove_extension: + * @path : path + * + * Removes the extension from the path and returns the result. + * Removes all text after and including the last '.'. + * Only '.'s after the last slash are considered. + * + * Returns: path with the extension part removed. + */ +char *path_remove_extension(char *path) +{ + char *last = (char*)strrchr(path_basename(path), '.'); + if (!last) + return NULL; + if (*last) + *last = '\0'; + return last; +} + +/** + * path_is_compressed_file: + * @path : path + * + * Checks if path is a compressed file. + * + * Returns: true (1) if path is a compressed file, otherwise false (0). + **/ +bool path_is_compressed_file(const char* path) +{ + const char *ext = path_get_extension(path); + + if ( strcasestr(ext, "zip") + || strcasestr(ext, "apk") + || strcasestr(ext, "7z")) + return true; + + return false; +} + +/** + * path_file_exists: + * @path : path + * + * Checks if a file already exists at the specified path (@path). + * + * Returns: true (1) if file already exists, otherwise false (0). + */ +bool path_file_exists(const char *path) +{ + FILE *dummy; + + if (!path || !*path) + return false; + + dummy = fopen(path, "rb"); + + if (!dummy) + return false; + + fclose(dummy); + return true; +} + +/** + * fill_pathname: + * @out_path : output path + * @in_path : input path + * @replace : what to replace + * @size : buffer size of output path + * + * FIXME: Verify + * + * Replaces filename extension with 'replace' and outputs result to out_path. + * The extension here is considered to be the string from the last '.' + * to the end. + * + * Only '.'s after the last slash are considered as extensions. + * If no '.' is present, in_path and replace will simply be concatenated. + * 'size' is buffer size of 'out_path'. + * E.g.: in_path = "/foo/bar/baz/boo.c", replace = ".asm" => + * out_path = "/foo/bar/baz/boo.asm" + * E.g.: in_path = "/foo/bar/baz/boo.c", replace = "" => + * out_path = "/foo/bar/baz/boo" + */ +void fill_pathname(char *out_path, const char *in_path, + const char *replace, size_t size) +{ + char tmp_path[PATH_MAX_LENGTH]; + char *tok = NULL; + + tmp_path[0] = '\0'; + + strlcpy(tmp_path, in_path, sizeof(tmp_path)); + if ((tok = (char*)strrchr(path_basename(tmp_path), '.'))) + *tok = '\0'; + + fill_pathname_noext(out_path, tmp_path, replace, size); +} + +/** + * fill_pathname_noext: + * @out_path : output path + * @in_path : input path + * @replace : what to replace + * @size : buffer size of output path + * + * Appends a filename extension 'replace' to 'in_path', and outputs + * result in 'out_path'. + * + * Assumes in_path has no extension. If an extension is still + * present in 'in_path', it will be ignored. + * + */ +void fill_pathname_noext(char *out_path, const char *in_path, + const char *replace, size_t size) +{ + strlcpy(out_path, in_path, size); + strlcat(out_path, replace, size); +} + +char *find_last_slash(const char *str) +{ + const char *slash = strrchr(str, '/'); +#ifdef _WIN32 + const char *backslash = strrchr(str, '\\'); + + if (backslash && ((slash && backslash > slash) || !slash)) + slash = backslash; +#endif + + return (char*)slash; +} + +/** + * fill_pathname_slash: + * @path : path + * @size : size of path + * + * Assumes path is a directory. Appends a slash + * if not already there. + **/ +void fill_pathname_slash(char *path, size_t size) +{ + size_t path_len = strlen(path); + const char *last_slash = find_last_slash(path); + + /* Try to preserve slash type. */ + if (last_slash && (last_slash != (path + path_len - 1))) + { + char join_str[2]; + + join_str[0] = '\0'; + + strlcpy(join_str, last_slash, sizeof(join_str)); + strlcat(path, join_str, size); + } + else if (!last_slash) + strlcat(path, path_default_slash(), size); +} + +/** + * fill_pathname_dir: + * @in_dir : input directory path + * @in_basename : input basename to be appended to @in_dir + * @replace : replacement to be appended to @in_basename + * @size : size of buffer + * + * Appends basename of 'in_basename', to 'in_dir', along with 'replace'. + * Basename of in_basename is the string after the last '/' or '\\', + * i.e the filename without directories. + * + * If in_basename has no '/' or '\\', the whole 'in_basename' will be used. + * 'size' is buffer size of 'in_dir'. + * + * E.g..: in_dir = "/tmp/some_dir", in_basename = "/some_content/foo.c", + * replace = ".asm" => in_dir = "/tmp/some_dir/foo.c.asm" + **/ +void fill_pathname_dir(char *in_dir, const char *in_basename, + const char *replace, size_t size) +{ + const char *base = NULL; + + fill_pathname_slash(in_dir, size); + base = path_basename(in_basename); + strlcat(in_dir, base, size); + strlcat(in_dir, replace, size); +} + +/** + * fill_pathname_base: + * @out : output path + * @in_path : input path + * @size : size of output path + * + * Copies basename of @in_path into @out_path. + **/ +void fill_pathname_base(char *out, const char *in_path, size_t size) +{ + const char *ptr = path_basename(in_path); + + if (!ptr) + ptr = in_path; + + strlcpy(out, ptr, size); +} + +void fill_pathname_base_noext(char *out, const char *in_path, size_t size) +{ + fill_pathname_base(out, in_path, size); + path_remove_extension(out); +} + +void fill_pathname_base_ext(char *out, const char *in_path, const char *ext, + size_t size) +{ + fill_pathname_base_noext(out, in_path, size); + strlcat(out, ext, size); +} + +/** + * fill_pathname_basedir: + * @out_dir : output directory + * @in_path : input path + * @size : size of output directory + * + * Copies base directory of @in_path into @out_path. + * If in_path is a path without any slashes (relative current directory), + * @out_path will get path "./". + **/ +void fill_pathname_basedir(char *out_dir, + const char *in_path, size_t size) +{ + if (out_dir != in_path) + strlcpy(out_dir, in_path, size); + path_basedir(out_dir); +} + +void fill_pathname_basedir_noext(char *out_dir, + const char *in_path, size_t size) +{ + fill_pathname_basedir(out_dir, in_path, size); + path_remove_extension(out_dir); +} + +/** + * fill_pathname_parent_dir: + * @out_dir : output directory + * @in_dir : input directory + * @size : size of output directory + * + * Copies parent directory of @in_dir into @out_dir. + * Assumes @in_dir is a directory. Keeps trailing '/'. + **/ +void fill_pathname_parent_dir(char *out_dir, + const char *in_dir, size_t size) +{ + if (out_dir != in_dir) + strlcpy(out_dir, in_dir, size); + path_parent_dir(out_dir); +} + +/** + * fill_dated_filename: + * @out_filename : output filename + * @ext : extension of output filename + * @size : buffer size of output filename + * + * Creates a 'dated' filename prefixed by 'RetroArch', and + * concatenates extension (@ext) to it. + * + * E.g.: + * out_filename = "RetroArch-{month}{day}-{Hours}{Minutes}.{@ext}" + **/ +void fill_dated_filename(char *out_filename, + const char *ext, size_t size) +{ + time_t cur_time = time(NULL); + + strftime(out_filename, size, + "RetroArch-%m%d-%H%M%S.", localtime(&cur_time)); + strlcat(out_filename, ext, size); +} + +/** + * fill_str_dated_filename: + * @out_filename : output filename + * @in_str : input string + * @ext : extension of output filename + * @size : buffer size of output filename + * + * Creates a 'dated' filename prefixed by the string @in_str, and + * concatenates extension (@ext) to it. + * + * E.g.: + * out_filename = "RetroArch-{year}{month}{day}-{Hour}{Minute}{Second}.{@ext}" + **/ +void fill_str_dated_filename(char *out_filename, + const char *in_str, const char *ext, size_t size) +{ + char format[256]; + time_t cur_time = time(NULL); + + format[0] = '\0'; + + strftime(format, sizeof(format), "-%y%m%d-%H%M%S.", localtime(&cur_time)); + strlcpy(out_filename, in_str, size); + strlcat(out_filename, format, size); + strlcat(out_filename, ext, size); +} + +/** + * path_basedir: + * @path : path + * + * Extracts base directory by mutating path. + * Keeps trailing '/'. + **/ +void path_basedir(char *path) +{ + char *last = NULL; + if (strlen(path) < 2) + return; + + last = find_last_slash(path); + + if (last) + last[1] = '\0'; + else + snprintf(path, 3, ".%s", path_default_slash()); +} + +/** + * path_parent_dir: + * @path : path + * + * Extracts parent directory by mutating path. + * Assumes that path is a directory. Keeps trailing '/'. + **/ +void path_parent_dir(char *path) +{ + size_t len = strlen(path); + if (len && path_char_is_slash(path[len - 1])) + path[len - 1] = '\0'; + path_basedir(path); +} + +/** + * path_basename: + * @path : path + * + * Get basename from @path. + * + * Returns: basename from path. + **/ +const char *path_basename(const char *path) +{ + /* We cut either at the first compression-related hash + * or the last slash; whichever comes last */ + const char *last = find_last_slash(path); + const char *delim = path_get_archive_delim(path); + + if (delim) + return delim + 1; + + if (last) + return last + 1; + + return path; +} + +/** + * path_is_absolute: + * @path : path + * + * Checks if @path is an absolute path or a relative path. + * + * Returns: true if path is absolute, false if path is relative. + **/ +bool path_is_absolute(const char *path) +{ + if (path[0] == '/') + return true; +#ifdef _WIN32 + /* Many roads lead to Rome ... */ + if (( strstr(path, "\\\\") == path) + || strstr(path, ":/") + || strstr(path, ":\\") + || strstr(path, ":\\\\")) + return true; +#endif + return false; +} + +/** + * path_resolve_realpath: + * @buf : buffer for path + * @size : size of buffer + * + * Turns relative paths into absolute path. + * If relative, rebases on current working dir. + **/ +void path_resolve_realpath(char *buf, size_t size) +{ +#ifndef RARCH_CONSOLE + char tmp[PATH_MAX_LENGTH]; + + tmp[0] = '\0'; + + strlcpy(tmp, buf, sizeof(tmp)); + +#ifdef _WIN32 + if (!_fullpath(buf, tmp, size)) + strlcpy(buf, tmp, size); +#else + + /* NOTE: realpath() expects at least PATH_MAX_LENGTH bytes in buf. + * Technically, PATH_MAX_LENGTH needn't be defined, but we rely on it anyways. + * POSIX 2008 can automatically allocate for you, + * but don't rely on that. */ + if (!realpath(tmp, buf)) + strlcpy(buf, tmp, size); +#endif +#endif +} + +/** + * fill_pathname_resolve_relative: + * @out_path : output path + * @in_refpath : input reference path + * @in_path : input path + * @size : size of @out_path + * + * Joins basedir of @in_refpath together with @in_path. + * If @in_path is an absolute path, out_path = in_path. + * E.g.: in_refpath = "/foo/bar/baz.a", in_path = "foobar.cg", + * out_path = "/foo/bar/foobar.cg". + **/ +void fill_pathname_resolve_relative(char *out_path, + const char *in_refpath, const char *in_path, size_t size) +{ + if (path_is_absolute(in_path)) + { + strlcpy(out_path, in_path, size); + return; + } + + fill_pathname_basedir(out_path, in_refpath, size); + strlcat(out_path, in_path, size); +} + +/** + * fill_pathname_join: + * @out_path : output path + * @dir : directory + * @path : path + * @size : size of output path + * + * Joins a directory (@dir) and path (@path) together. + * Makes sure not to get two consecutive slashes + * between directory and path. + **/ +void fill_pathname_join(char *out_path, + const char *dir, const char *path, size_t size) +{ + if (out_path != dir) + strlcpy(out_path, dir, size); + + if (*out_path) + fill_pathname_slash(out_path, size); + + strlcat(out_path, path, size); +} + +void fill_pathname_join_special_ext(char *out_path, + const char *dir, const char *path, + const char *last, const char *ext, + size_t size) +{ + fill_pathname_join(out_path, dir, path, size); + if (*out_path) + fill_pathname_slash(out_path, size); + + strlcat(out_path, last, size); + strlcat(out_path, ext, size); +} + +void fill_pathname_join_concat(char *out_path, + const char *dir, const char *path, + const char *concat, + size_t size) +{ + fill_pathname_join(out_path, dir, path, size); + strlcat(out_path, concat, size); +} + +void fill_pathname_join_noext(char *out_path, + const char *dir, const char *path, size_t size) +{ + fill_pathname_join(out_path, dir, path, size); + path_remove_extension(out_path); +} + + +/** + * fill_pathname_join_delim: + * @out_path : output path + * @dir : directory + * @path : path + * @delim : delimiter + * @size : size of output path + * + * Joins a directory (@dir) and path (@path) together + * using the given delimiter (@delim). + **/ +void fill_pathname_join_delim(char *out_path, const char *dir, + const char *path, const char delim, size_t size) +{ + size_t copied = strlcpy(out_path, dir, size); + + out_path[copied] = delim; + out_path[copied+1] = '\0'; + + strlcat(out_path, path, size); +} + +void fill_pathname_join_delim_concat(char *out_path, const char *dir, + const char *path, const char delim, const char *concat, + size_t size) +{ + fill_pathname_join_delim(out_path, dir, path, delim, size); + strlcat(out_path, concat, size); +} + +/** + * fill_short_pathname_representation: + * @out_rep : output representation + * @in_path : input path + * @size : size of output representation + * + * Generates a short representation of path. It should only + * be used for displaying the result; the output representation is not + * binding in any meaningful way (for a normal path, this is the same as basename) + * In case of more complex URLs, this should cut everything except for + * the main image file. + * + * E.g.: "/path/to/game.img" -> game.img + * "/path/to/myarchive.7z#folder/to/game.img" -> game.img + */ +void fill_short_pathname_representation(char* out_rep, + const char *in_path, size_t size) +{ + char path_short[PATH_MAX_LENGTH]; + + path_short[0] = '\0'; + + fill_pathname(path_short, path_basename(in_path), "", + sizeof(path_short)); + + strlcpy(out_rep, path_short, size); +} + +void fill_short_pathname_representation_noext(char* out_rep, + const char *in_path, size_t size) +{ + fill_short_pathname_representation(out_rep, in_path, size); + path_remove_extension(out_rep); +} diff --git a/libretro/libretro-common/file/nbio/nbio_stdio.c b/libretro/libretro-common/file/nbio/nbio_stdio.c new file mode 100644 index 0000000..826d7a4 --- /dev/null +++ b/libretro/libretro-common/file/nbio/nbio_stdio.c @@ -0,0 +1,205 @@ +#include +#include + +#include + +struct nbio_t +{ + FILE* f; + void* data; + size_t progress; + size_t len; + /* + * possible values: + * NBIO_READ, NBIO_WRITE - obvious + * -1 - currently doing nothing + * -2 - the pointer was reallocated since the last operation + */ + signed char op; + signed char mode; +}; + +static const char * modes[]={ "rb", "wb", "r+b", "rb", "wb", "r+b" }; + +struct nbio_t* nbio_open(const char * filename, unsigned mode) +{ + void *buf = NULL; + struct nbio_t* handle = NULL; + size_t len = 0; + FILE* f = fopen(filename, modes[mode]); + if (!f) + return NULL; + + handle = (struct nbio_t*)malloc(sizeof(struct nbio_t)); + + if (!handle) + goto error; + + handle->f = f; + + switch (mode) + { + case NBIO_WRITE: + case BIO_WRITE: + break; + default: + fseek(handle->f, 0, SEEK_END); + len = ftell(handle->f); + break; + } + + handle->mode = mode; + + if (len) + buf = malloc(len); + + if (!buf) + goto error; + + handle->data = buf; + handle->len = len; + handle->progress = handle->len; + handle->op = -2; + + return handle; + +error: + if (handle) + free(handle); + fclose(f); + return NULL; +} + +void nbio_begin_read(struct nbio_t* handle) +{ + if (!handle) + return; + + if (handle->op >= 0) + { + puts("ERROR - attempted file read operation while busy"); + abort(); + } + + fseek(handle->f, 0, SEEK_SET); + + handle->op = NBIO_READ; + handle->progress = 0; +} + +void nbio_begin_write(struct nbio_t* handle) +{ + if (!handle) + return; + + if (handle->op >= 0) + { + puts("ERROR - attempted file write operation while busy"); + abort(); + } + + fseek(handle->f, 0, SEEK_SET); + handle->op = NBIO_WRITE; + handle->progress = 0; +} + +bool nbio_iterate(struct nbio_t* handle) +{ + size_t amount = 65536; + + if (!handle) + return false; + + if (amount > handle->len - handle->progress) + amount = handle->len - handle->progress; + + switch (handle->op) + { + case NBIO_READ: + if (handle->mode == BIO_READ) + { + amount = handle->len; + fread((char*)handle->data, 1, amount, handle->f); + } + else + fread((char*)handle->data + handle->progress, 1, amount, handle->f); + break; + case NBIO_WRITE: + if (handle->mode == BIO_WRITE) + { + size_t written = 0; + amount = handle->len; + written = fwrite((char*)handle->data, 1, amount, handle->f); + if (written != amount) + return false; + } + else + fwrite((char*)handle->data + handle->progress, 1, amount, handle->f); + break; + } + + handle->progress += amount; + + if (handle->progress == handle->len) + handle->op = -1; + return (handle->op < 0); +} + +void nbio_resize(struct nbio_t* handle, size_t len) +{ + if (!handle) + return; + + if (handle->op >= 0) + { + puts("ERROR - attempted file resize operation while busy"); + abort(); + } + if (len < handle->len) + { + puts("ERROR - attempted file shrink operation, not implemented"); + abort(); + } + + handle->len = len; + handle->data = realloc(handle->data, handle->len); + handle->op = -1; + handle->progress = handle->len; +} + +void* nbio_get_ptr(struct nbio_t* handle, size_t* len) +{ + if (!handle) + return NULL; + if (len) + *len = handle->len; + if (handle->op == -1) + return handle->data; + return NULL; +} + +void nbio_cancel(struct nbio_t* handle) +{ + if (!handle) + return; + + handle->op = -1; + handle->progress = handle->len; +} + +void nbio_free(struct nbio_t* handle) +{ + if (!handle) + return; + if (handle->op >= 0) + { + puts("ERROR - attempted free() while busy"); + abort(); + } + fclose(handle->f); + free(handle->data); + + handle->f = NULL; + handle->data = NULL; + free(handle); +} diff --git a/libretro/libretro-common/file/retro_dirent.c b/libretro/libretro-common/file/retro_dirent.c new file mode 100644 index 0000000..26f3e8a --- /dev/null +++ b/libretro/libretro-common/file/retro_dirent.c @@ -0,0 +1,231 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (retro_dirent.c). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include + +#include + +#include +#include + +#if defined(_WIN32) +# ifdef _MSC_VER +# define setmode _setmode +# endif +#include +# ifdef _XBOX +# include +# define INVALID_FILE_ATTRIBUTES -1 +# else +# include +# include +# include +# include +# endif +#elif defined(VITA) +# include +# include +#include +#else +# if defined(PSP) +# include +# endif +# include +# include +# include +# include +#endif + +#ifdef __CELLOS_LV2__ +#include +#endif + +#if (defined(__CELLOS_LV2__) && !defined(__PSL1GHT__)) || defined(__QNX__) || defined(PSP) +#include /* stat() is defined here */ +#endif + +struct RDIR +{ +#if defined(_WIN32) + WIN32_FIND_DATA entry; + HANDLE directory; + bool next; + char path[PATH_MAX_LENGTH]; +#elif defined(VITA) || defined(PSP) + SceUID directory; + SceIoDirent entry; +#elif defined(__CELLOS_LV2__) + CellFsErrno error; + int directory; + CellFsDirent entry; +#else + DIR *directory; + const struct dirent *entry; +#endif +}; + +struct RDIR *retro_opendir(const char *name) +{ +#if defined(_WIN32) + char path_buf[1024]; +#endif + struct RDIR *rdir = (struct RDIR*)calloc(1, sizeof(*rdir)); + + if (!rdir) + return NULL; + +#if defined(_WIN32) + path_buf[0] = '\0'; + snprintf(path_buf, sizeof(path_buf), "%s\\*", name); + rdir->directory = FindFirstFile(path_buf, &rdir->entry); +#elif defined(VITA) || defined(PSP) + rdir->directory = sceIoDopen(name); +#elif defined(_3DS) + rdir->directory = (name && *name)? opendir(name) : NULL; + rdir->entry = NULL; +#elif defined(__CELLOS_LV2__) + rdir->error = cellFsOpendir(name, &rdir->directory); +#else + rdir->directory = opendir(name); + rdir->entry = NULL; +#endif + + return rdir; +} + +bool retro_dirent_error(struct RDIR *rdir) +{ +#if defined(_WIN32) + return (rdir->directory == INVALID_HANDLE_VALUE); +#elif defined(VITA) || defined(PSP) + return (rdir->directory < 0); +#elif defined(__CELLOS_LV2__) + return (rdir->error != CELL_FS_SUCCEEDED); +#else + return !(rdir->directory); +#endif +} + +int retro_readdir(struct RDIR *rdir) +{ +#if defined(_WIN32) + if(rdir->next) + return (FindNextFile(rdir->directory, &rdir->entry) != 0); + + rdir->next = true; + return (rdir->directory != INVALID_HANDLE_VALUE); +#elif defined(VITA) || defined(PSP) + return (sceIoDread(rdir->directory, &rdir->entry) > 0); +#elif defined(__CELLOS_LV2__) + uint64_t nread; + rdir->error = cellFsReaddir(rdir->directory, &rdir->entry, &nread); + return (nread != 0); +#else + return ((rdir->entry = readdir(rdir->directory)) != NULL); +#endif +} + +const char *retro_dirent_get_name(struct RDIR *rdir) +{ +#if defined(_WIN32) + return rdir->entry.cFileName; +#elif defined(VITA) || defined(PSP) || defined(__CELLOS_LV2__) + return rdir->entry.d_name; +#else + return rdir->entry->d_name; +#endif +} + +/** + * + * retro_dirent_is_dir: + * @rdir : pointer to the directory entry. + * @path : path to the directory entry. + * + * Is the directory listing entry a directory? + * + * Returns: true if directory listing entry is + * a directory, false if not. + */ +bool retro_dirent_is_dir(struct RDIR *rdir, const char *path) +{ +#if defined(_WIN32) + const WIN32_FIND_DATA *entry = (const WIN32_FIND_DATA*)&rdir->entry; + return entry->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; +#elif defined(PSP) || defined(VITA) + const SceIoDirent *entry = (const SceIoDirent*)&rdir->entry; +#if defined(PSP) + return (entry->d_stat.st_attr & FIO_SO_IFDIR) == FIO_SO_IFDIR; +#elif defined(VITA) + return SCE_S_ISDIR(entry->d_stat.st_mode); +#endif +#elif defined(__CELLOS_LV2__) + CellFsDirent *entry = (CellFsDirent*)&rdir->entry; + return (entry->d_type == CELL_FS_TYPE_DIRECTORY); +#else + struct stat buf; +#if defined(DT_DIR) + const struct dirent *entry = (const struct dirent*)rdir->entry; + if (entry->d_type == DT_DIR) + return true; + /* This can happen on certain file systems. */ + if (!(entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK)) + return false; +#endif + /* dirent struct doesn't have d_type, do it the slow way ... */ + if (stat(path, &buf) < 0) + return false; + return S_ISDIR(buf.st_mode); +#endif +} + +void retro_dirent_include_hidden(struct RDIR *rdir, bool include_hidden) +{ +#ifdef _WIN32 + if (include_hidden) + rdir->entry.dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN; + else + rdir->entry.dwFileAttributes &= ~FILE_ATTRIBUTE_HIDDEN; +#endif +} + +void retro_closedir(struct RDIR *rdir) +{ + if (!rdir) + return; + +#if defined(_WIN32) + if (rdir->directory != INVALID_HANDLE_VALUE) + FindClose(rdir->directory); +#elif defined(VITA) || defined(PSP) + sceIoDclose(rdir->directory); +#elif defined(__CELLOS_LV2__) + rdir->error = cellFsClosedir(rdir->directory); +#else + if (rdir->directory) + closedir(rdir->directory); +#endif + + free(rdir); +} diff --git a/libretro/libretro-common/include/boolean.h b/libretro/libretro-common/include/boolean.h new file mode 100644 index 0000000..4d53907 --- /dev/null +++ b/libretro/libretro-common/include/boolean.h @@ -0,0 +1,39 @@ +/* Copyright (C) 2010-2016 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (boolean.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_BOOLEAN_H +#define __LIBRETRO_SDK_BOOLEAN_H + +#ifndef __cplusplus + +#if defined(_MSC_VER) && !defined(SN_TARGET_PS3) +/* Hack applied for MSVC when compiling in C89 mode as it isn't C99 compliant. */ +#define bool unsigned char +#define true 1 +#define false 0 +#else +#include +#endif + +#endif + +#endif diff --git a/libretro/libretro-common/include/compat/apple_compat.h b/libretro/libretro-common/include/compat/apple_compat.h new file mode 100644 index 0000000..f656546 --- /dev/null +++ b/libretro/libretro-common/include/compat/apple_compat.h @@ -0,0 +1,84 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (apple_compat.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __APPLE_COMPAT_H +#define __APPLE_COMPAT_H + +#ifdef __APPLE__ +#include +#endif + +#ifdef __OBJC__ + +#if (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4) +typedef int NSInteger; +typedef unsigned NSUInteger; +typedef float CGFloat; +#endif + +#ifndef __has_feature +/* Compatibility with non-Clang compilers. */ +#define __has_feature(x) 0 +#endif + +#ifndef CF_RETURNS_RETAINED +#if __has_feature(attribute_cf_returns_retained) +#define CF_RETURNS_RETAINED __attribute__((cf_returns_retained)) +#else +#define CF_RETURNS_RETAINED +#endif +#endif + +#ifndef NS_INLINE +#define NS_INLINE inline +#endif + +NS_INLINE CF_RETURNS_RETAINED CFTypeRef CFBridgingRetainCompat(id X) +{ +#if __has_feature(objc_arc) + return (__bridge_retained CFTypeRef)X; +#else + return X; +#endif +} + +#endif + +#ifdef IOS +#ifndef __IPHONE_5_0 +#warning "This project uses features only available in iOS SDK 5.0 and later." +#endif + +#ifdef __OBJC__ +#import +#import +#import +#endif + +#else + +#ifdef __OBJC__ +#include +#endif +#endif + +#endif diff --git a/libretro/libretro-common/include/compat/fnmatch.h b/libretro/libretro-common/include/compat/fnmatch.h new file mode 100644 index 0000000..3f3c025 --- /dev/null +++ b/libretro/libretro-common/include/compat/fnmatch.h @@ -0,0 +1,30 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (fnmatch.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_FNMATCH_H__ +#define __LIBRETRO_SDK_COMPAT_FNMATCH_H__ + +#define FNM_NOMATCH 1 + +int rl_fnmatch(const char *pattern, const char *string, int flags); + +#endif diff --git a/libretro/libretro-common/include/compat/getopt.h b/libretro/libretro-common/include/compat/getopt.h new file mode 100644 index 0000000..fd5300a --- /dev/null +++ b/libretro/libretro-common/include/compat/getopt.h @@ -0,0 +1,75 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (getopt.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_GETOPT_H +#define __LIBRETRO_SDK_COMPAT_GETOPT_H + +#if defined(RARCH_INTERNAL) && defined(HAVE_CONFIG_H) +#include "../../../config.h" +#endif + +/* Custom implementation of the GNU getopt_long for portability. + * Not designed to be fully compatible, but compatible with + * the features RetroArch uses. */ + +#ifdef HAVE_GETOPT_LONG +#include +#else +/* Avoid possible naming collisions during link since we + * prefer to use the actual name. */ +#define getopt_long(argc, argv, optstring, longopts, longindex) __getopt_long_retro(argc, argv, optstring, longopts, longindex) + +#include + +RETRO_BEGIN_DECLS + +struct option +{ + const char *name; + int has_arg; + int *flag; + int val; +}; + +/* argv[] is declared with char * const argv[] in GNU, + * but this makes no sense, as non-POSIX getopt_long + * mutates argv (non-opts are moved to the end). */ +int getopt_long(int argc, char *argv[], + const char *optstring, const struct option *longopts, int *longindex); +extern char *optarg; +extern int optind, opterr, optopt; + +RETRO_END_DECLS + +/* If these are variously #defined, then we have bigger problems */ +#ifndef no_argument + #define no_argument 0 + #define required_argument 1 + #define optional_argument 2 +#endif + +/* HAVE_GETOPT_LONG */ +#endif + +/* pragma once */ +#endif + diff --git a/libretro/libretro-common/include/compat/ifaddrs.h b/libretro/libretro-common/include/compat/ifaddrs.h new file mode 100644 index 0000000..2dc6848 --- /dev/null +++ b/libretro/libretro-common/include/compat/ifaddrs.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1995, 1999 + * Berkeley Software Design, Inc. 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. + * + * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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. + * + * BSDI ifaddrs.h,v 2.5 2000/02/23 14:51:59 dab Exp + */ + +#ifndef _IFADDRS_H_ +#define _IFADDRS_H_ + +struct ifaddrs +{ + struct ifaddrs *ifa_next; + char *ifa_name; + unsigned int ifa_flags; + struct sockaddr *ifa_addr; + struct sockaddr *ifa_netmask; + struct sockaddr *ifa_dstaddr; + void *ifa_data; +}; + +/* + * This may have been defined in . Note that if is + * to be included it must be included before this header file. + */ +#ifndef ifa_broadaddr +#define ifa_broadaddr ifa_dstaddr /* broadcast address interface */ +#endif + +#include + +extern int getifaddrs(struct ifaddrs **ifap); +extern void freeifaddrs(struct ifaddrs *ifa); + +#endif diff --git a/libretro/libretro-common/include/compat/intrinsics.h b/libretro/libretro-common/include/compat/intrinsics.h new file mode 100644 index 0000000..f8e2176 --- /dev/null +++ b/libretro/libretro-common/include/compat/intrinsics.h @@ -0,0 +1,85 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (intrinsics.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_INTRINSICS_H +#define __LIBRETRO_SDK_COMPAT_INTRINSICS_H + +#include +#include +#include + +#include +#include + +#if defined(_MSC_VER) && !defined(_XBOX) +#if (_MSC_VER > 1310) +#include +#endif +#endif + +RETRO_BEGIN_DECLS + +/* Count Leading Zero, unsigned 16bit input value */ +static INLINE unsigned compat_clz_u16(uint16_t val) +{ +#ifdef __GNUC__ + return __builtin_clz(val << 16 | 0x8000); +#else + unsigned ret = 0; + + while(!(val & 0x8000) && ret < 16) + { + val <<= 1; + ret++; + } + + return ret; +#endif +} + +/* Count Trailing Zero */ +static INLINE int compat_ctz(unsigned x) +{ +#if defined(__GNUC__) && !defined(RARCH_CONSOLE) + return __builtin_ctz(x); +#elif _MSC_VER >= 1400 && !defined(_XBOX) + unsigned long r = 0; + _BitScanReverse((unsigned long*)&r, x); + return (int)r; +#else +/* Only checks at nibble granularity, + * because that's what we need. */ + if (x & 0x000f) + return 0; + if (x & 0x00f0) + return 4; + if (x & 0x0f00) + return 8; + if (x & 0xf000) + return 12; + return 16; +#endif +} + +RETRO_END_DECLS + +#endif diff --git a/libretro/libretro-common/include/compat/msvc.h b/libretro/libretro-common/include/compat/msvc.h new file mode 100644 index 0000000..8319b5d --- /dev/null +++ b/libretro/libretro-common/include/compat/msvc.h @@ -0,0 +1,132 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (msvc.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_MSVC_H +#define __LIBRETRO_SDK_COMPAT_MSVC_H + +#ifdef _MSC_VER + +#ifdef __cplusplus +extern "C" { +#endif + +/* Pre-MSVC 2015 compilers don't implement snprintf in a cross-platform manner. */ +#if _MSC_VER < 1900 + #include + #ifndef snprintf + #define snprintf c99_snprintf_retro__ + #endif + + int c99_snprintf_retro__(char *outBuf, size_t size, const char *format, ...); +#endif + +/* Pre-MSVC 2010 compilers don't implement vsnprintf in a cross-platform manner? Not sure about this one. */ +#if _MSC_VER < 1600 + #include + #include + #ifndef vsnprintf + #define vsnprintf c99_vsnprintf_retro__ + #endif + int c99_vsnprintf_retro__(char *outBuf, size_t size, const char *format, va_list ap); +#endif + +#ifdef __cplusplus +} +#endif + +#undef UNICODE /* Do not bother with UNICODE at this time. */ +#include +#include +#include + +/* Python headers defines ssize_t and sets HAVE_SSIZE_T. + * Cannot duplicate these efforts. + */ +#ifndef HAVE_SSIZE_T +#if defined(_WIN64) +typedef __int64 ssize_t; +#elif defined(_WIN32) +typedef int ssize_t; +#endif +#endif + +#define mkdir(dirname, unused) _mkdir(dirname) +#define strtoull _strtoui64 +#undef strcasecmp +#define strcasecmp _stricmp +#undef strncasecmp +#define strncasecmp _strnicmp + +/* Disable some of the annoying warnings. */ +#pragma warning(disable : 4800) +#pragma warning(disable : 4805) +#pragma warning(disable : 4244) +#pragma warning(disable : 4305) +#pragma warning(disable : 4146) +#pragma warning(disable : 4267) +#pragma warning(disable : 4723) +#pragma warning(disable : 4996) + +/* roundf and va_copy is available since MSVC 2013 */ +#if _MSC_VER < 1800 +#define roundf(in) (in >= 0.0f ? floorf(in + 0.5f) : ceilf(in - 0.5f)) +#define va_copy(x, y) ((x) = (y)) +#endif + +#if _MSC_VER <= 1200 + #ifndef __cplusplus + /* VC6 math.h doesn't define some functions when in C mode. + * Trying to define a prototype gives "undefined reference". + * But providing an implementation then gives "function already has body". + * So the equivalent of the implementations from math.h are used as + * defines here instead, and it seems to work. + */ + #define cosf(x) ((float)cos((double)x)) + #define powf(x, y) ((float)pow((double)x, (double)y)) + #define sinf(x) ((float)sin((double)x)) + #define ceilf(x) ((float)ceil((double)x)) + #define floorf(x) ((float)floor((double)x)) + #define sqrtf(x) ((float)sqrt((double)x)) + #endif + + #ifndef _vscprintf + #define _vscprintf c89_vscprintf_retro__ + int c89_vscprintf_retro__(const char *format, va_list pargs); + #endif + + #ifndef _strtoui64 + #define _strtoui64(x, y, z) (_atoi64(x)) + #endif + +#endif + +#ifndef PATH_MAX +#define PATH_MAX _MAX_PATH +#endif + +#ifndef SIZE_MAX +#define SIZE_MAX _UI32_MAX +#endif + +#endif +#endif + diff --git a/libretro/libretro-common/include/compat/msvc/stdint.h b/libretro/libretro-common/include/compat/msvc/stdint.h new file mode 100644 index 0000000..fa7a2bf --- /dev/null +++ b/libretro/libretro-common/include/compat/msvc/stdint.h @@ -0,0 +1,258 @@ +/* ISO C9x compliant stdint.h for Microsoft Visual Studio + * Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 + * + * Copyright (c) 2006-2008 Alexander Chemeris + * + * 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. The name of the author may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef __RARCH_STDINT_H +#define __RARCH_STDINT_H + +#if _MSC_VER && (_MSC_VER < 1600) +/* Pre-MSVC 2010 needs an implementation of stdint.h. */ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +/* For Visual Studio 6 in C++ mode and for many Visual Studio versions when + * compiling for ARM we should wrap include with 'extern "C++" {}' + * or compiler give many errors like this: + * + * error C2733: second C linkage of overloaded function 'wmemchr' not allowed + */ +#ifdef __cplusplus +#if _MSC_VER <= 1200 +extern "C++" { +#else +extern "C" { +#endif +#endif +# include +#ifdef __cplusplus +} +#endif + +/* Define _W64 macros to mark types changing their size, like intptr_t. */ +#ifndef _W64 +# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +# define _W64 __w64 +# else +# define _W64 +# endif +#endif + + +/* 7.18.1 Integer types. */ + +/* 7.18.1.1 Exact-width integer types. */ + +/* Visual Studio 6 and Embedded Visual C++ 4 doesn't + * realize that, e.g. char has the same size as __int8 + * so we give up on __intX for them. + */ +#if (_MSC_VER < 1300) + typedef signed char int8_t; + typedef signed short int16_t; + typedef signed int int32_t; + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; +#else + typedef signed __int8 int8_t; + typedef signed __int16 int16_t; + typedef signed __int32 int32_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; +#endif +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; + + +/* 7.18.1.2 Minimum-width integer types. */ +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +/* 7.18.1.3 Fastest minimum-width integer types. */ +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; + +/* 7.18.1.4 Integer types capable of holding object pointers. */ +#ifdef _WIN64 /* [ */ + typedef signed __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else /* _WIN64 ][ */ + typedef _W64 signed int intptr_t; + typedef _W64 unsigned int uintptr_t; +#endif /* _WIN64 ] */ + +/* 7.18.1.5 Greatest-width integer types. */ +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + +/* 7.18.2 Limits of specified-width integer types. */ + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) +/* [ See footnote 220 at page 257 and footnote 221 at page 259. */ + +/* 7.18.2.1 Limits of exact-width integer types. */ +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX + +/* 7.18.2.2 Limits of minimum-width integer types. */ +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +/* 7.18.2.3 Limits of fastest minimum-width integer types. */ +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +/* 7.18.2.4 Limits of integer types capable of holding object pointers. */ +#ifdef _WIN64 /* [ */ +# define INTPTR_MIN INT64_MIN +# define INTPTR_MAX INT64_MAX +# define UINTPTR_MAX UINT64_MAX +#else /* _WIN64 ][ */ +# define INTPTR_MIN INT32_MIN +# define INTPTR_MAX INT32_MAX +# define UINTPTR_MAX UINT32_MAX +#endif /* _WIN64 ] */ + +/* 7.18.2.5 Limits of greatest-width integer types */ +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +/* 7.18.3 Limits of other integer types */ + +#ifdef _WIN64 /* [ */ +# define PTRDIFF_MIN _I64_MIN +# define PTRDIFF_MAX _I64_MAX +#else /* _WIN64 ][ */ +# define PTRDIFF_MIN _I32_MIN +# define PTRDIFF_MAX _I32_MAX +#endif /* _WIN64 ] */ + +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX + +#ifndef SIZE_MAX /* [ */ +# ifdef _WIN64 /* [ */ +# define SIZE_MAX _UI64_MAX +# else /* _WIN64 ][ */ +# define SIZE_MAX _UI32_MAX +# endif /* _WIN64 ] */ +#endif /* SIZE_MAX ] */ + +/* WCHAR_MIN and WCHAR_MAX are also defined in */ +#ifndef WCHAR_MIN /* [ */ +# define WCHAR_MIN 0 +#endif /* WCHAR_MIN ] */ +#ifndef WCHAR_MAX // [ +# define WCHAR_MAX _UI16_MAX +#endif /* WCHAR_MAX ] */ + +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX + +#endif /* __STDC_LIMIT_MACROS ] */ + +/* 7.18.4 Limits of other integer types */ + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) +/* [ See footnote 224 at page 260 */ + +/* 7.18.4.1 Macros for minimum-width integer constants */ + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +/* 7.18.4.2 Macros for greatest-width integer constants */ +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C + +#endif +/* __STDC_CONSTANT_MACROS ] */ + +#else +/* Sanity for everything else. */ +#include +#endif + +#endif + diff --git a/libretro/libretro-common/include/compat/posix_string.h b/libretro/libretro-common/include/compat/posix_string.h new file mode 100644 index 0000000..380e1a1 --- /dev/null +++ b/libretro/libretro-common/include/compat/posix_string.h @@ -0,0 +1,61 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (posix_string.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_POSIX_STRING_H +#define __LIBRETRO_SDK_COMPAT_POSIX_STRING_H + +#include + +#ifdef _MSC_VER +#include +#endif + +RETRO_BEGIN_DECLS + +#ifdef _WIN32 +#undef strtok_r +#define strtok_r(str, delim, saveptr) retro_strtok_r__(str, delim, saveptr) + +char *strtok_r(char *str, const char *delim, char **saveptr); +#endif + +#ifdef _MSC_VER +#undef strcasecmp +#undef strdup +#define strcasecmp(a, b) retro_strcasecmp__(a, b) +#define strdup(orig) retro_strdup__(orig) +int strcasecmp(const char *a, const char *b); +char *strdup(const char *orig); + +/* isblank is available since MSVC 2013 */ +#if _MSC_VER < 1800 +#undef isblank +#define isblank(c) retro_isblank__(c) +int isblank(int c); +#endif + +#endif + + +RETRO_END_DECLS + +#endif diff --git a/libretro/libretro-common/include/compat/strcasestr.h b/libretro/libretro-common/include/compat/strcasestr.h new file mode 100644 index 0000000..a8676a5 --- /dev/null +++ b/libretro/libretro-common/include/compat/strcasestr.h @@ -0,0 +1,49 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (strcasestr.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_STRCASESTR_H +#define __LIBRETRO_SDK_COMPAT_STRCASESTR_H + +#include + +#if defined(RARCH_INTERNAL) && defined(HAVE_CONFIG_H) +#include "../../../config.h" +#endif + +#ifndef HAVE_STRCASESTR + +#include + +RETRO_BEGIN_DECLS + +/* Avoid possible naming collisions during link + * since we prefer to use the actual name. */ +#define strcasestr(haystack, needle) strcasestr_retro__(haystack, needle) + +char *strcasestr(const char *haystack, const char *needle); + +RETRO_END_DECLS + +#endif + +#endif + diff --git a/libretro/libretro-common/include/compat/strl.h b/libretro/libretro-common/include/compat/strl.h new file mode 100644 index 0000000..a68005a --- /dev/null +++ b/libretro/libretro-common/include/compat/strl.h @@ -0,0 +1,58 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (strl.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_COMPAT_STRL_H +#define __LIBRETRO_SDK_COMPAT_STRL_H + +#include +#include + +#ifdef HAVE_CONFIG_H +#include "../../../config.h" +#endif + +#include + +RETRO_BEGIN_DECLS + +#ifdef __MACH__ +#ifndef HAVE_STRL +#define HAVE_STRL +#endif +#endif + +#ifndef HAVE_STRL +/* Avoid possible naming collisions during link since + * we prefer to use the actual name. */ +#define strlcpy(dst, src, size) strlcpy_retro__(dst, src, size) + +#define strlcat(dst, src, size) strlcat_retro__(dst, src, size) + +size_t strlcpy(char *dest, const char *source, size_t size); +size_t strlcat(char *dest, const char *source, size_t size); + +#endif + +RETRO_END_DECLS + +#endif + diff --git a/libretro/libretro-common/include/compat/zconf.h b/libretro/libretro-common/include/compat/zconf.h new file mode 100644 index 0000000..007b644 --- /dev/null +++ b/libretro/libretro-common/include/compat/zconf.h @@ -0,0 +1,483 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzvprintf z_gzvprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateGetDictionary z_inflateGetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# endif +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/libretro/libretro-common/include/compat/zconf.h.in b/libretro/libretro-common/include/compat/zconf.h.in new file mode 100644 index 0000000..007b644 --- /dev/null +++ b/libretro/libretro-common/include/compat/zconf.h.in @@ -0,0 +1,483 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzvprintf z_gzvprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateGetDictionary z_inflateGetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# endif +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/libretro/libretro-common/include/compat/zlib.h b/libretro/libretro-common/include/compat/zlib.h new file mode 100644 index 0000000..60fa3be --- /dev/null +++ b/libretro/libretro-common/include/compat/zlib.h @@ -0,0 +1,1780 @@ +#ifndef _COMPAT_ZLIB_H +#define _COMPAT_ZLIB_H + +#ifdef WANT_ZLIB + +#ifdef RARCH_INTERNAL +#include "zconf.h.in" +#endif + +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.8, April 28th, 2013 + + Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.8" +#define ZLIB_VERNUM 0x1280 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 8 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) (voidpf opaque, uInt items, uInt size); +typedef void (*free_func) (voidpf opaque, voidpf address); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + void *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use in the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + + const char * zlibVersion (void); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* + int deflateInit (z_streamp strm, int level); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + + int deflate (z_streamp strm, int flush); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). Some + output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed code + block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the stream + are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least the + value returned by deflateBound (see below). Then deflate is guaranteed to + return Z_STREAM_END. If not enough output space is provided, deflate will + not return Z_STREAM_END, and it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect the + compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + + int deflateEnd (z_streamp strm); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* + int inflateInit (z_streamp strm); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the + exact value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit() does not process any header information -- that is deferred + until inflate() is called. +*/ + + + int inflate (z_streamp strm, int flush); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing will + resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained, so applications that need that information should + instead use raw inflate, see inflateInit2() below, or inflateBack() and + perform their own processing of the gzip header and trailer. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + producted so far. The CRC-32 is checked against the gzip trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is desired. +*/ + + + int inflateEnd (z_streamp strm); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* + int deflateInit2 (z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + + int deflateSetDictionary (z_streamp strm, + const Bytef *dictionary, + uInt dictLength); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + + int deflateCopy (z_streamp dest, + z_streamp source); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + + int deflateReset (z_streamp strm); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. The + stream will keep the same compression level and any other attributes that + may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + + int deflateParams (z_streamp strm, + int level, + int strategy); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression level is changed, the input available so far is + compressed with the old level (and may be flushed); the new level will take + effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to be + compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if + strm->avail_out was zero. +*/ + + int deflateTune (z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + + uLong deflateBound (z_streamp strm, + uLong sourceLen); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + + int deflatePending (z_streamp strm, + unsigned *pending, + int *bits); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + + int deflatePrime (z_streamp strm, + int bits, + int value); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + + int deflateSetHeader (z_streamp strm, + gz_headerp head); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* + int inflateInit2 (z_streamp strm, + int windowBits); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + + int inflateSetDictionary (z_streamp strm, + const Bytef *dictionary, + uInt dictLength); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + + int inflateGetDictionary (z_streamp strm, + Bytef *dictionary, + uInt *dictLength); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + + int inflateSync (z_streamp strm); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + + int inflateCopy (z_streamp dest, + z_streamp source); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + + int inflateReset (z_streamp strm); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + + int inflateReset2 (z_streamp strm, + int windowBits); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + + int inflatePrime (z_streamp strm, + int bits, + int value); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + + long inflateMark (z_streamp strm); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above or -1 << 16 if the provided + source stream state was inconsistent. +*/ + + int inflateGetHeader (z_streamp strm, + gz_headerp head); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* + int inflateBackInit (z_streamp strm, int windowBits, + unsigned char FAR *window); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) (void FAR *, + z_const unsigned char FAR * FAR *); +typedef int (*out_func) (void FAR *, unsigned char FAR *, unsigned); + + int inflateBack (z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the normal + behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + + int inflateBackEnd (z_streamp strm); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + + uLong zlibCompileFlags (void); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + + int compress (Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + + int compress2 (Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + + uLong compressBound (uLong sourceLen); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + + int uncompress (unsigned char *dest, uint32_t *destLen, + const unsigned char *source, uint32_t sourceLen); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* + gzFile gzopen (const char *path, const char *mode); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + + gzFile gzdopen (int fd, const char *mode); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + + int gzbuffer (gzFile file, unsigned size); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Two buffers are allocated, either both of the specified size when + writing, or one of the specified size and the other twice that size when + reading. A larger buffer size of, for example, 64K or 128K bytes will + noticeably increase the speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + + int gzsetparams (gzFile file, int level, int strategy); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + + int gzread (gzFile file, voidp buf, unsigned len); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. +*/ + + int gzwrite (gzFile file, + voidpc buf, unsigned len); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + + int gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or 0 in case of error. The number of + uncompressed bytes written is limited to 8191, or one less than the buffer + size given to gzbuffer(). The caller should assure that this limit is not + exceeded. If it is exceeded, then gzprintf() will return an error (0) with + nothing written. In this case, there may also be a buffer overflow with + unpredictable consequences, which is possible only if zlib was compiled with + the insecure functions sprintf() or vsprintf() because the secure snprintf() + or vsnprintf() functions were not available. This can be determined using + zlibCompileFlags(). +*/ + + int gzputs (gzFile file, const char *s); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + + char * gzgets (gzFile file, char *buf, int len); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + + int gzputc (gzFile file, int c); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + + int gzgetc (gzFile file); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + + int gzungetc (int c, gzFile file); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + + int gzflush (gzFile file, int flush); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatented gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* + z_off_t gzseek (gzFile file, + z_off_t offset, int whence); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + + int gzrewind (gzFile file); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* + z_off_t gztell (gzFile file); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* + z_off_t gzoffset (gzFile file); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + + int gzeof (gzFile file); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + + int gzdirect (gzFile file); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + + int gzclose (gzFile file); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + + int gzclose_r (gzFile file); + int gzclose_w (gzFile file); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + + const char * gzerror (gzFile file, int *errnum); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + + void gzclearerr (gzFile file); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +uint32_t adler32 (uint32_t adler, const uint8_t *buf, size_t len); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +/* + uLong adler32_combine (uLong adler1, uLong adler2, + z_off_t len2); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + + uLong crc32 (uLong crc, const Bytef *buf, uInt len); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +/* + uLong crc32_combine (uLong crc1, uLong crc2, z_off_t len2); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ + int deflateInit_ (z_streamp strm, int level, + const char *version, int stream_size); + int inflateInit_ (z_streamp strm, + const char *version, int stream_size); + int deflateInit2_ (z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size); + int inflateInit2_ (z_streamp strm, int windowBits, + const char *version, int stream_size); + int inflateBackInit_ (z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ + int gzgetc_ (gzFile file); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + gzFile gzopen64 (const char *, const char *); + z_off64_t gzseek64 (gzFile, z_off64_t, int); + z_off64_t gztell64 (gzFile); + z_off64_t gzoffset64 (gzFile); + uLong adler32_combine64 (uLong, uLong, z_off64_t); + uLong crc32_combine64 (uLong, uLong, z_off64_t); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + gzFile gzopen64 (const char *, const char *); + z_off_t gzseek64 (gzFile, z_off_t, int); + z_off_t gztell64 (gzFile); + z_off_t gzoffset64 (gzFile); + uLong adler32_combine64 (uLong, uLong, z_off_t); + uLong crc32_combine64 (uLong, uLong, z_off_t); +# endif +#else + gzFile gzopen (const char *, const char *); + z_off_t gzseek (gzFile, z_off_t, int); + z_off_t gztell (gzFile); + z_off_t gzoffset (gzFile); + uLong adler32_combine (uLong, uLong, z_off_t); + uLong crc32_combine (uLong, uLong, z_off_t); +#endif + +#else /* Z_SOLO */ + + uLong adler32_combine (uLong, uLong, z_off_t); + uLong crc32_combine (uLong, uLong, z_off_t); + +#endif /* !Z_SOLO */ + +/* hack for buggy compilers */ +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; +#endif + +/* undocumented functions */ + const char * zError (int); + int inflateSyncPoint (z_streamp); + +const uint32_t * get_crc_table(void); + int inflateUndermine (z_streamp, int); + int inflateResetKeep (z_streamp); + int deflateResetKeep (z_streamp); +#if defined(_WIN32) && !defined(Z_SOLO) + gzFile gzopen_w (const wchar_t *path, + const char *mode); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO + int gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ + +#else +#include +#endif + +#endif diff --git a/libretro/libretro-common/include/compat/zutil.h b/libretro/libretro-common/include/compat/zutil.h new file mode 100644 index 0000000..bce9a48 --- /dev/null +++ b/libretro/libretro-common/include/compat/zutil.h @@ -0,0 +1,253 @@ +#ifndef _COMPAT_ZUTIL_H +#define _COMPAT_ZUTIL_H + +#ifdef WANT_ZLIB + +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern char z_errmsg[10][21]; /* indexed by 2-zlib_error */ +/* (array size given to avoid silly warnings with Visual C++) */ +/* (array entry size given to avoid silly string cast warnings) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + uLong adler32_combine64 (uLong, uLong, z_off_t); + uLong crc32_combine64 (uLong, uLong, z_off_t); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy (Bytef* dest, const Bytef* source, uInt len); + int ZLIB_INTERNAL zmemcmp (const Bytef* s1, const Bytef* s2, uInt len); + void ZLIB_INTERNAL zmemzero (Bytef* dest, uInt len); +#endif + +/* Diagnostic functions */ +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, + unsigned size); + void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ + +#else +#include +#endif + +#endif diff --git a/libretro/libretro-common/include/file/archive_file.h b/libretro/libretro-common/include/file/archive_file.h new file mode 100644 index 0000000..b2b5971 --- /dev/null +++ b/libretro/libretro-common/include/file/archive_file.h @@ -0,0 +1,213 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (archive_file.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LIBRETRO_SDK_ARCHIVE_FILE_H__ +#define LIBRETRO_SDK_ARCHIVE_FILE_H__ + +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +#include + +#include + +RETRO_BEGIN_DECLS + +enum file_archive_transfer_type +{ + ARCHIVE_TRANSFER_NONE = 0, + ARCHIVE_TRANSFER_INIT, + ARCHIVE_TRANSFER_ITERATE, + ARCHIVE_TRANSFER_DEINIT, + ARCHIVE_TRANSFER_DEINIT_ERROR +}; + +typedef struct file_archive_handle +{ + void *stream; + uint8_t *data; + uint32_t real_checksum; + const struct file_archive_file_backend *backend; +} file_archive_file_handle_t; + +typedef struct file_archive_file_data file_archive_file_data_t; + +typedef struct file_archive_transfer +{ + enum file_archive_transfer_type type; + int32_t archive_size; + file_archive_file_data_t *handle; + void *stream; + const uint8_t *footer; + const uint8_t *directory; + const uint8_t *data; + const struct file_archive_file_backend *backend; +} file_archive_transfer_t; + +enum file_archive_compression_mode +{ + ARCHIVE_MODE_UNCOMPRESSED = 0, + ARCHIVE_MODE_COMPRESSED = 8 +}; + +struct decomp_state_t +{ + char *opt_file; + char *needle; + void **buf; + size_t size; + bool found; +}; + +typedef struct +{ + char *source_file; + char *subdir; + char *target_dir; + char *target_file; + char *valid_ext; + + char *callback_error; + + file_archive_transfer_t archive; +} decompress_state_t; + +struct archive_extract_userdata +{ + char archive_path[PATH_MAX_LENGTH]; + char *first_extracted_file_path; + char *extracted_file_path; + const char *extraction_directory; + size_t archive_path_size; + struct string_list *ext; + struct string_list *list; + bool found_file; + bool list_only; + void *context; + char archive_name[PATH_MAX_LENGTH]; + uint32_t crc; + struct decomp_state_t decomp_state; + decompress_state_t *dec; +}; + +/* Returns true when parsing should continue. False to stop. */ +typedef int (*file_archive_file_cb)(const char *name, const char *valid_exts, + const uint8_t *cdata, unsigned cmode, uint32_t csize, uint32_t size, + uint32_t crc32, struct archive_extract_userdata *userdata); + +struct file_archive_file_backend +{ + void *(*stream_new)(void); + void (*stream_free)(void *); + bool (*stream_decompress_data_to_file_init)( + file_archive_file_handle_t *, const uint8_t *, uint32_t, uint32_t); + int (*stream_decompress_data_to_file_iterate)(void *); + uint32_t (*stream_crc_calculate)(uint32_t, const uint8_t *, size_t); + int (*compressed_file_read)(const char *path, const char *needle, void **buf, + const char *optional_outfile); + int (*archive_parse_file_init)( + file_archive_transfer_t *state, + const char *file); + int (*archive_parse_file_iterate_step)( + file_archive_transfer_t *state, + const char *valid_exts, + struct archive_extract_userdata *userdata, + file_archive_file_cb file_cb); + const char *ident; +}; + +int file_archive_parse_file_iterate( + file_archive_transfer_t *state, + bool *returnerr, + const char *file, + const char *valid_exts, + file_archive_file_cb file_cb, + struct archive_extract_userdata *userdata); + +void file_archive_parse_file_iterate_stop(file_archive_transfer_t *state); + +int file_archive_parse_file_progress(file_archive_transfer_t *state); + +/** + * file_archive_extract_file: + * @archive_path : filename path to ZIP archive. + * @archive_path_size : size of ZIP archive. + * @valid_exts : valid extensions for a file. + * @extraction_directory : the directory to extract the temporary + * file to. + * + * Extract file from archive. If no file inside the archive is + * specified, the first file found will be used. + * + * Returns : true (1) on success, otherwise false (0). + **/ +bool file_archive_extract_file(char *archive_path, size_t archive_path_size, + const char *valid_exts, const char *extraction_dir, + char *out_path, size_t len); + +/** + * file_archive_get_file_list: + * @path : filename path of archive + * @valid_exts : Valid extensions of archive to be parsed. + * If NULL, allow all. + * + * Returns: string listing of files from archive on success, otherwise NULL. + **/ +struct string_list* file_archive_get_file_list(const char *path, const char *valid_exts); + +bool file_archive_perform_mode(const char *name, const char *valid_exts, + const uint8_t *cdata, unsigned cmode, uint32_t csize, uint32_t size, + uint32_t crc32, struct archive_extract_userdata *userdata); + +int file_archive_compressed_read( + const char* path, void **buf, + const char* optional_filename, ssize_t *length); + +const struct file_archive_file_backend* file_archive_get_zlib_file_backend(void); +const struct file_archive_file_backend* file_archive_get_7z_file_backend(void); + +const struct file_archive_file_backend* file_archive_get_file_backend(const char *path); + +/** + * file_archive_get_file_crc32: + * @path : filename path of archive + * + * Returns: CRC32 of the specified file in the archive, otherwise 0. + * If no path within the archive is specified, the first + * file found inside is used. + **/ +uint32_t file_archive_get_file_crc32(const char *path); + +extern const struct file_archive_file_backend zlib_backend; +extern const struct file_archive_file_backend sevenzip_backend; + +RETRO_END_DECLS + +#endif + diff --git a/libretro/libretro-common/include/file/config_file.h b/libretro/libretro-common/include/file/config_file.h new file mode 100644 index 0000000..3e26acf --- /dev/null +++ b/libretro/libretro-common/include/file/config_file.h @@ -0,0 +1,166 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (config_file.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef __LIBRETRO_SDK_CONFIG_FILE_H +#define __LIBRETRO_SDK_CONFIG_FILE_H + +#include + +RETRO_BEGIN_DECLS + +#include +#include +#include + +#include + +#define CONFIG_GET_BOOL_BASE(conf, base, var, key) do { \ + bool tmp = false; \ + if (config_get_bool(conf, key, &tmp)) \ + base->var = tmp; \ +} while(0) + +#define CONFIG_GET_INT_BASE(conf, base, var, key) do { \ + int tmp = 0; \ + if (config_get_int(conf, key, &tmp)) \ + base->var = tmp; \ +} while(0) + +#define CONFIG_GET_FLOAT_BASE(conf, base, var, key) do { \ + float tmp = 0.0f; \ + if (config_get_float(conf, key, &tmp)) \ + base->var = tmp; \ +} while(0) + +typedef struct config_file config_file_t; + +/* Config file format + * - # are treated as comments. Rest of the line is ignored. + * - Format is: key = value. There can be as many spaces as you like in-between. + * - Value can be wrapped inside "" for multiword strings. (foo = "hai u") + * - #include includes a config file in-place. + * + * Path is relative to where config file was loaded unless an absolute path is chosen. + * Key/value pairs from an #include are read-only, and cannot be modified. + */ + +/* Loads a config file. Returns NULL if file doesn't exist. + * NULL path will create an empty config file. */ +config_file_t *config_file_new(const char *path); + +/* Load a config file from a string. */ +config_file_t *config_file_new_from_string(const char *from_string); + +/* Frees config file. */ +void config_file_free(config_file_t *conf); + +/* Loads a new config, and appends its data to conf. + * The key-value pairs of the new config file takes priority over the old. */ +bool config_append_file(config_file_t *conf, const char *path); + +/* All extract functions return true when value is valid and exists. + * Returns false otherwise. */ + +bool config_entry_exists(config_file_t *conf, const char *entry); + +struct config_entry_list; +struct config_file_entry +{ + const char *key; + const char *value; + /* Used intentionally. Opaque here. */ + const struct config_entry_list *next; +}; + +bool config_get_entry_list_head(config_file_t *conf, struct config_file_entry *entry); +bool config_get_entry_list_next(struct config_file_entry *entry); + +/* Extracts a double from config file. */ +bool config_get_double(config_file_t *conf, const char *entry, double *in); + +/* Extracts a float from config file. */ +bool config_get_float(config_file_t *conf, const char *entry, float *in); + +/* Extracts an int from config file. */ +bool config_get_int(config_file_t *conf, const char *entry, int *in); + +/* Extracts an uint from config file. */ +bool config_get_uint(config_file_t *conf, const char *entry, unsigned *in); + +#if defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L +/* Extracts an uint64 from config file. */ +bool config_get_uint64(config_file_t *conf, const char *entry, uint64_t *in); +#endif + +/* Extracts an unsigned int from config file treating input as hex. */ +bool config_get_hex(config_file_t *conf, const char *entry, unsigned *in); + +/* Extracts a single char. If value consists of several chars, + * this is an error. */ +bool config_get_char(config_file_t *conf, const char *entry, char *in); + +/* Extracts an allocated string in *in. This must be free()-d if + * this function succeeds. */ +bool config_get_string(config_file_t *conf, const char *entry, char **in); + +/* Extracts a string to a preallocated buffer. Avoid memory allocation. */ +bool config_get_array(config_file_t *conf, const char *entry, char *s, size_t len); + +/* Extracts a string to a preallocated buffer. Avoid memory allocation. + * Recognized magic like ~/. Similar to config_get_array() otherwise. */ +bool config_get_path(config_file_t *conf, const char *entry, char *s, size_t len); + +/* Extracts a string to a preallocated buffer. Avoid memory allocation. */ +bool config_get_config_path(config_file_t *conf, char *s, size_t len); + +/* Extracts a boolean from config. + * Valid boolean true are "true" and "1". Valid false are "false" and "0". + * Other values will be treated as an error. */ +bool config_get_bool(config_file_t *conf, const char *entry, bool *in); + +/* Setters. Similar to the getters. + * Will not write to entry if the entry was obtained from an #include. */ +void config_set_double(config_file_t *conf, const char *entry, double value); +void config_set_float(config_file_t *conf, const char *entry, float value); +void config_set_int(config_file_t *conf, const char *entry, int val); +void config_set_hex(config_file_t *conf, const char *entry, unsigned val); +void config_set_uint64(config_file_t *conf, const char *entry, uint64_t val); +void config_set_char(config_file_t *conf, const char *entry, char val); +void config_set_string(config_file_t *conf, const char *entry, const char *val); +void config_unset(config_file_t *conf, const char *key); +void config_set_path(config_file_t *conf, const char *entry, const char *val); +void config_set_bool(config_file_t *conf, const char *entry, bool val); + +/* Write the current config to a file. */ +bool config_file_write(config_file_t *conf, const char *path); + +/* Dump the current config to an already opened file. + * Does not close the file. */ +void config_file_dump(config_file_t *conf, FILE *file); + +bool config_file_exists(const char *path); + +RETRO_END_DECLS + +#endif + diff --git a/libretro/libretro-common/include/file/config_file_userdata.h b/libretro/libretro-common/include/file/config_file_userdata.h new file mode 100644 index 0000000..0c433ed --- /dev/null +++ b/libretro/libretro-common/include/file/config_file_userdata.h @@ -0,0 +1,61 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (config_file_userdata.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef _LIBRETRO_SDK_CONFIG_FILE_USERDATA_H +#define _LIBRETRO_SDK_CONFIG_FILE_USERDATA_H + +#include + +#include + +#include + +RETRO_BEGIN_DECLS + +struct config_file_userdata +{ + config_file_t *conf; + const char *prefix[2]; +}; + +int config_userdata_get_float(void *userdata, const char *key_str, + float *value, float default_value); + +int config_userdata_get_int(void *userdata, const char *key_str, + int *value, int default_value); + +int config_userdata_get_float_array(void *userdata, const char *key_str, + float **values, unsigned *out_num_values, + const float *default_values, unsigned num_default_values); + +int config_userdata_get_int_array(void *userdata, const char *key_str, + int **values, unsigned *out_num_values, + const int *default_values, unsigned num_default_values); + +int config_userdata_get_string(void *userdata, const char *key_str, + char **output, const char *default_output); + +void config_userdata_free(void *ptr); + +RETRO_END_DECLS + +#endif diff --git a/libretro/libretro-common/include/file/file_path.h b/libretro/libretro-common/include/file/file_path.h new file mode 100644 index 0000000..c92e35c --- /dev/null +++ b/libretro/libretro-common/include/file/file_path.h @@ -0,0 +1,471 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (file_path.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_FILE_PATH_H +#define __LIBRETRO_SDK_FILE_PATH_H + +#include +#include +#include +#include + +#include + +#include + +RETRO_BEGIN_DECLS + +/* Order in this enum is equivalent to negative sort order in filelist + * (i.e. DIRECTORY is on top of PLAIN_FILE) */ +enum +{ + RARCH_FILETYPE_UNSET, + RARCH_PLAIN_FILE, + RARCH_COMPRESSED_FILE_IN_ARCHIVE, + RARCH_COMPRESSED_ARCHIVE, + RARCH_DIRECTORY, + RARCH_FILE_UNSUPPORTED +}; + + +/** + * path_is_compressed_file: + * @path : path + * + * Checks if path is a compressed file. + * + * Returns: true (1) if path is a compressed file, otherwise false (0). + **/ +bool path_is_compressed_file(const char *path); + +/** + * path_contains_compressed_file: + * @path : path + * + * Checks if path contains a compressed file. + * + * Currently we only check for hash symbol (#) inside the pathname. + * If path is ever expanded to a general URI, we should check for that here. + * + * Example: Somewhere in the path there might be a compressed file + * E.g.: /path/to/file.7z#mygame.img + * + * Returns: true (1) if path contains compressed file, otherwise false (0). + **/ +#define path_contains_compressed_file(path) (path_get_archive_delim((path)) != NULL) + +/** + * path_file_exists: + * @path : path + * + * Checks if a file already exists at the specified path (@path). + * + * Returns: true (1) if file already exists, otherwise false (0). + */ +bool path_file_exists(const char *path); + +/** + * path_get_archive_delim: + * @path : path + * + * Gets delimiter of an archive file. Only the first '#' + * after a compression extension is considered. + * + * Returns: pointer to the delimiter in the path if it contains + * a compressed file, otherwise NULL. + */ +const char *path_get_archive_delim(const char *path); + +/** + * path_get_extension: + * @path : path + * + * Gets extension of file. Only '.'s + * after the last slash are considered. + * + * Returns: extension part from the path. + */ +const char *path_get_extension(const char *path); + +/** + * path_remove_extension: + * @path : path + * + * Removes the extension from the path and returns the result. + * Removes all text after and including the last '.'. + * Only '.'s after the last slash are considered. + * + * Returns: path with the extension part removed. + */ +char *path_remove_extension(char *path); + +/** + * path_basename: + * @path : path + * + * Get basename from @path. + * + * Returns: basename from path. + **/ +const char *path_basename(const char *path); + +/** + * path_basedir: + * @path : path + * + * Extracts base directory by mutating path. + * Keeps trailing '/'. + **/ +void path_basedir(char *path); + +/** + * path_parent_dir: + * @path : path + * + * Extracts parent directory by mutating path. + * Assumes that path is a directory. Keeps trailing '/'. + **/ +void path_parent_dir(char *path); + +/** + * path_resolve_realpath: + * @buf : buffer for path + * @size : size of buffer + * + * Turns relative paths into absolute path. + * If relative, rebases on current working dir. + **/ +void path_resolve_realpath(char *buf, size_t size); + +/** + * path_is_absolute: + * @path : path + * + * Checks if @path is an absolute path or a relative path. + * + * Returns: true if path is absolute, false if path is relative. + **/ +bool path_is_absolute(const char *path); + +/** + * fill_pathname: + * @out_path : output path + * @in_path : input path + * @replace : what to replace + * @size : buffer size of output path + * + * FIXME: Verify + * + * Replaces filename extension with 'replace' and outputs result to out_path. + * The extension here is considered to be the string from the last '.' + * to the end. + * + * Only '.'s after the last slash are considered as extensions. + * If no '.' is present, in_path and replace will simply be concatenated. + * 'size' is buffer size of 'out_path'. + * E.g.: in_path = "/foo/bar/baz/boo.c", replace = ".asm" => + * out_path = "/foo/bar/baz/boo.asm" + * E.g.: in_path = "/foo/bar/baz/boo.c", replace = "" => + * out_path = "/foo/bar/baz/boo" + */ +void fill_pathname(char *out_path, const char *in_path, + const char *replace, size_t size); + +/** + * fill_dated_filename: + * @out_filename : output filename + * @ext : extension of output filename + * @size : buffer size of output filename + * + * Creates a 'dated' filename prefixed by 'RetroArch', and + * concatenates extension (@ext) to it. + * + * E.g.: + * out_filename = "RetroArch-{month}{day}-{Hours}{Minutes}.{@ext}" + **/ +void fill_dated_filename(char *out_filename, + const char *ext, size_t size); + +/** + * fill_str_dated_filename: + * @out_filename : output filename + * @in_str : input string + * @ext : extension of output filename + * @size : buffer size of output filename + * + * Creates a 'dated' filename prefixed by the string @in_str, and + * concatenates extension (@ext) to it. + * + * E.g.: + * out_filename = "RetroArch-{year}{month}{day}-{Hour}{Minute}{Second}.{@ext}" + **/ +void fill_str_dated_filename(char *out_filename, + const char *in_str, const char *ext, size_t size); + +/** + * fill_pathname_noext: + * @out_path : output path + * @in_path : input path + * @replace : what to replace + * @size : buffer size of output path + * + * Appends a filename extension 'replace' to 'in_path', and outputs + * result in 'out_path'. + * + * Assumes in_path has no extension. If an extension is still + * present in 'in_path', it will be ignored. + * + */ +void fill_pathname_noext(char *out_path, const char *in_path, + const char *replace, size_t size); + +/** + * find_last_slash: + * @str : input path + * + * Gets a pointer to the last slash in the input path. + * + * Returns: a pointer to the last slash in the input path. + **/ +char *find_last_slash(const char *str); + +/** + * fill_pathname_dir: + * @in_dir : input directory path + * @in_basename : input basename to be appended to @in_dir + * @replace : replacement to be appended to @in_basename + * @size : size of buffer + * + * Appends basename of 'in_basename', to 'in_dir', along with 'replace'. + * Basename of in_basename is the string after the last '/' or '\\', + * i.e the filename without directories. + * + * If in_basename has no '/' or '\\', the whole 'in_basename' will be used. + * 'size' is buffer size of 'in_dir'. + * + * E.g..: in_dir = "/tmp/some_dir", in_basename = "/some_content/foo.c", + * replace = ".asm" => in_dir = "/tmp/some_dir/foo.c.asm" + **/ +void fill_pathname_dir(char *in_dir, const char *in_basename, + const char *replace, size_t size); + +/** + * fill_pathname_base: + * @out : output path + * @in_path : input path + * @size : size of output path + * + * Copies basename of @in_path into @out_path. + **/ +void fill_pathname_base(char *out_path, const char *in_path, size_t size); + +void fill_pathname_base_noext(char *out_dir, + const char *in_path, size_t size); + +void fill_pathname_base_ext(char *out, + const char *in_path, const char *ext, + size_t size); + +/** + * fill_pathname_basedir: + * @out_dir : output directory + * @in_path : input path + * @size : size of output directory + * + * Copies base directory of @in_path into @out_path. + * If in_path is a path without any slashes (relative current directory), + * @out_path will get path "./". + **/ +void fill_pathname_basedir(char *out_path, const char *in_path, size_t size); + +void fill_pathname_basedir_noext(char *out_dir, + const char *in_path, size_t size); + +/** + * fill_pathname_parent_dir: + * @out_dir : output directory + * @in_dir : input directory + * @size : size of output directory + * + * Copies parent directory of @in_dir into @out_dir. + * Assumes @in_dir is a directory. Keeps trailing '/'. + **/ +void fill_pathname_parent_dir(char *out_dir, + const char *in_dir, size_t size); + +/** + * fill_pathname_resolve_relative: + * @out_path : output path + * @in_refpath : input reference path + * @in_path : input path + * @size : size of @out_path + * + * Joins basedir of @in_refpath together with @in_path. + * If @in_path is an absolute path, out_path = in_path. + * E.g.: in_refpath = "/foo/bar/baz.a", in_path = "foobar.cg", + * out_path = "/foo/bar/foobar.cg". + **/ +void fill_pathname_resolve_relative(char *out_path, const char *in_refpath, + const char *in_path, size_t size); + +/** + * fill_pathname_join: + * @out_path : output path + * @dir : directory + * @path : path + * @size : size of output path + * + * Joins a directory (@dir) and path (@path) together. + * Makes sure not to get two consecutive slashes + * between directory and path. + **/ +void fill_pathname_join(char *out_path, const char *dir, + const char *path, size_t size); + +void fill_pathname_join_special_ext(char *out_path, + const char *dir, const char *path, + const char *last, const char *ext, + size_t size); + +void fill_pathname_join_concat(char *out_path, + const char *dir, const char *path, + const char *concat, + size_t size); + +void fill_pathname_join_noext(char *out_path, + const char *dir, const char *path, size_t size); + +/** + * fill_pathname_join_delim: + * @out_path : output path + * @dir : directory + * @path : path + * @delim : delimiter + * @size : size of output path + * + * Joins a directory (@dir) and path (@path) together + * using the given delimiter (@delim). + **/ +void fill_pathname_join_delim(char *out_path, const char *dir, + const char *path, const char delim, size_t size); + +void fill_pathname_join_delim_concat(char *out_path, const char *dir, + const char *path, const char delim, const char *concat, + size_t size); + +/** + * fill_short_pathname_representation: + * @out_rep : output representation + * @in_path : input path + * @size : size of output representation + * + * Generates a short representation of path. It should only + * be used for displaying the result; the output representation is not + * binding in any meaningful way (for a normal path, this is the same as basename) + * In case of more complex URLs, this should cut everything except for + * the main image file. + * + * E.g.: "/path/to/game.img" -> game.img + * "/path/to/myarchive.7z#folder/to/game.img" -> game.img + */ +void fill_short_pathname_representation(char* out_rep, + const char *in_path, size_t size); + +void fill_short_pathname_representation_noext(char* out_rep, + const char *in_path, size_t size); + +void fill_pathname_expand_special(char *out_path, + const char *in_path, size_t size); + +void fill_pathname_abbreviate_special(char *out_path, + const char *in_path, size_t size); + +/** + * path_char_is_slash: + * @c : character + * + * Checks if character (@c) is a slash. + * + * Returns: true (1) if character is a slash, otherwise false (0). + */ +#ifdef _WIN32 +#define path_char_is_slash(c) (((c) == '/') || ((c) == '\\')) +#else +#define path_char_is_slash(c) ((c) == '/') +#endif + +/** + * path_default_slash: + * + * Gets the default slash separator. + * + * Returns: default slash separator. + */ +#ifdef _WIN32 +#define path_default_slash() "\\" +#else +#define path_default_slash() "/" +#endif + +/** + * fill_pathname_slash: + * @path : path + * @size : size of path + * + * Assumes path is a directory. Appends a slash + * if not already there. + **/ +void fill_pathname_slash(char *path, size_t size); + +#ifndef RARCH_CONSOLE +void fill_pathname_application_path(char *buf, size_t size); +#endif + +/** + * path_mkdir: + * @dir : directory + * + * Create directory on filesystem. + * + * Returns: true (1) if directory could be created, otherwise false (0). + **/ +bool path_mkdir(const char *dir); + +/** + * path_is_directory: + * @path : path + * + * Checks if path is a directory. + * + * Returns: true (1) if path is a directory, otherwise false (0). + */ +bool path_is_directory(const char *path); + +bool path_is_character_special(const char *path); + +bool path_is_valid(const char *path); + +int32_t path_get_size(const char *path); + +RETRO_END_DECLS + +#endif diff --git a/libretro/libretro-common/include/file/nbio.h b/libretro/libretro-common/include/file/nbio.h new file mode 100644 index 0000000..011eef5 --- /dev/null +++ b/libretro/libretro-common/include/file/nbio.h @@ -0,0 +1,102 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (nbio.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_NBIO_H +#define __LIBRETRO_SDK_NBIO_H + +#include +#include + +#include + +RETRO_BEGIN_DECLS + +#ifndef NBIO_READ +#define NBIO_READ 0 +#endif + +#ifndef NBIO_WRITE +#define NBIO_WRITE 1 +#endif + +#ifndef NBIO_UPDATE +#define NBIO_UPDATE 2 +#endif + +#ifndef BIO_READ +#define BIO_READ 3 +#endif + +#ifndef BIO_WRITE +#define BIO_WRITE 4 +#endif + +struct nbio_t; + +/* + * Creates an nbio structure for performing the given operation on the given file. + */ +struct nbio_t* nbio_open(const char * filename, unsigned mode); + +/* + * Starts reading the given file. When done, it will be available in nbio_get_ptr. + * Can not be done if the structure was created with nbio_write. + */ +void nbio_begin_read(struct nbio_t* handle); + +/* + * Starts writing to the given file. Before this, you should've copied the data to nbio_get_ptr. + * Can not be done if the structure was created with nbio_read. + */ +void nbio_begin_write(struct nbio_t* handle); + +/* + * Performs part of the requested operation, or checks how it's going. + * When it returns true, it's done. + */ +bool nbio_iterate(struct nbio_t* handle); + +/* + * Resizes the file up to the given size; cannot shrink. + * Can not be done if the structure was created with nbio_read. + */ +void nbio_resize(struct nbio_t* handle, size_t len); + +/* + * Returns a pointer to the file data. Writable only if structure was not created with nbio_read. + * If any operation is in progress, the pointer will be NULL, but len will still be correct. + */ +void* nbio_get_ptr(struct nbio_t* handle, size_t* len); + +/* + * Stops any pending operation, allowing the object to be freed. + */ +void nbio_cancel(struct nbio_t* handle); + +/* + * Deletes the nbio structure and its associated pointer. + */ +void nbio_free(struct nbio_t* handle); + +RETRO_END_DECLS + +#endif diff --git a/libretro/libco/libco.h b/libretro/libretro-common/include/libco.h similarity index 97% rename from libretro/libco/libco.h rename to libretro/libretro-common/include/libco.h index 1599cb2..9925d7e 100644 --- a/libretro/libco/libco.h +++ b/libretro/libretro-common/include/libco.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2010-2017 The RetroArch team +/* Copyright (C) 2010-2016 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (libco.h). diff --git a/libretro/libretro-common/include/retro_common.h b/libretro/libretro-common/include/retro_common.h new file mode 100644 index 0000000..6e9e6bf --- /dev/null +++ b/libretro/libretro-common/include/retro_common.h @@ -0,0 +1,37 @@ +/* Copyright (C) 2010-2016 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (retro_common.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef _LIBRETRO_COMMON_RETRO_COMMON_H +#define _LIBRETRO_COMMON_RETRO_COMMON_H + +/* +This file is designed to normalize the libretro-common compiling environment. +It is not to be used in public API headers, as they should be designed as leanly as possible. +Nonetheless.. in the meantime, if you do something like use ssize_t, which is not fully portable, +in a public API, you may need this. +*/ + +/* conditional compilation is handled inside here */ +#include + +#endif + diff --git a/libretro/libco/retro_common_api.h b/libretro/libretro-common/include/retro_common_api.h similarity index 90% rename from libretro/libco/retro_common_api.h rename to libretro/libretro-common/include/retro_common_api.h index 659f90d..0532612 100644 --- a/libretro/libco/retro_common_api.h +++ b/libretro/libretro-common/include/retro_common_api.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2010-2017 The RetroArch team +/* Copyright (C) 2010-2016 The RetroArch team * * --------------------------------------------------------------------------------------- * The following license statement only applies to this file (retro_common_api.h). @@ -76,17 +76,17 @@ typedef int ssize_t; #endif #ifdef _WIN32 -#define STRING_REP_INT64 "%I64d" +#define STRING_REP_INT64 "%I64u" #define STRING_REP_UINT64 "%I64u" -#define STRING_REP_USIZE "%Iu" -#elif defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L && !defined(VITA) && !defined(WIIU) -#define STRING_REP_INT64 "%lld" +#define STRING_REP_ULONG "%Iu" +#elif defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L +#define STRING_REP_INT64 "%llu" #define STRING_REP_UINT64 "%llu" -#define STRING_REP_USIZE "%zu" +#define STRING_REP_ULONG "%zu" #else -#define STRING_REP_INT64 "%lld" +#define STRING_REP_INT64 "%llu" #define STRING_REP_UINT64 "%llu" -#define STRING_REP_USIZE "%lu" +#define STRING_REP_ULONG "%lu" #endif /* diff --git a/libretro/libretro-common/include/retro_environment.h b/libretro/libretro-common/include/retro_environment.h new file mode 100644 index 0000000..fa08ddc --- /dev/null +++ b/libretro/libretro-common/include/retro_environment.h @@ -0,0 +1,78 @@ +/* Copyright (C) 2010-2016 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (retro_environment.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_ENVIRONMENT_H +#define __LIBRETRO_SDK_ENVIRONMENT_H + +/* +This file is designed to create a normalized environment for compiling +libretro-common's private implementations, or any other sources which might +enjoy use of it's environment (RetroArch for instance). +This should be an elaborately crafted environment so that sources don't +need to be full of platform-specific workarounds. +*/ + +#if defined (__cplusplus) +#if 0 +printf("This is C++, version %d.\n", __cplusplus); +#endif +/* The expected values would be + * 199711L, for ISO/IEC 14882:1998 or 14882:2003 + */ + +#elif defined(__STDC__) +/* This is standard C. */ + +#if (__STDC__ == 1) +/* The implementation is ISO-conforming. */ +#define __STDC_ISO__ +#else +/* The implementation is not ISO-conforming. */ +#endif + +#if defined(__STDC_VERSION__) +#if (__STDC_VERSION__ >= 201112L) +/* This is C11. */ +#define __STDC_C11__ +#elif (__STDC_VERSION__ >= 199901L) +/* This is C99. */ +#define __STDC_C99__ +#elif (__STDC_VERSION__ >= 199409L) +/* This is C89 with amendment 1. */ +#define __STDC_C89__ +#define __STDC_C89_AMENDMENT_1__ +#else +/* This is C89 without amendment 1. */ +#define __STDC_C89__ +#endif +#else /* !defined(__STDC_VERSION__) */ +/* This is C89. __STDC_VERSION__ is not defined. */ +#define __STDC_C89__ +#endif + +#else /* !defined(__STDC__) */ +/* This is not standard C. __STDC__ is not defined. */ +#endif + + + +#endif diff --git a/libretro/libretro-common/include/retro_inline.h b/libretro/libretro-common/include/retro_inline.h new file mode 100644 index 0000000..8535d84 --- /dev/null +++ b/libretro/libretro-common/include/retro_inline.h @@ -0,0 +1,39 @@ +/* Copyright (C) 2010-2015 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (retro_inline.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __LIBRETRO_SDK_INLINE_H +#define __LIBRETRO_SDK_INLINE_H + +#ifndef INLINE + +#if !defined(__cplusplus) && defined(_WIN32) +#define INLINE _inline +#elif defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L +#define INLINE inline +#elif defined(__GNUC__) +#define INLINE __inline__ +#else +#define INLINE +#endif + +#endif +#endif diff --git a/libretro/libretro-common/include/retro_miscellaneous.h b/libretro/libretro-common/include/retro_miscellaneous.h new file mode 100644 index 0000000..b133550 --- /dev/null +++ b/libretro/libretro-common/include/retro_miscellaneous.h @@ -0,0 +1,194 @@ +/* Copyright (C) 2010-2016 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (retro_miscellaneous.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __RARCH_MISCELLANEOUS_H +#define __RARCH_MISCELLANEOUS_H + +#include +#include + +#if defined(__CELLOS_LV2__) && !defined(__PSL1GHT__) +#include +#elif defined(XENON) +#include