diff --git a/core/libs/prx/libcurl/CMakeLists.txt b/core/libs/prx/libcurl/CMakeLists.txt index 492c9382474a..c332c0c4616f 100644 --- a/core/libs/prx/libcurl/CMakeLists.txt +++ b/core/libs/prx/libcurl/CMakeLists.txt @@ -88,6 +88,7 @@ add_library(libcurl SHARED EXCLUDE_FROM_ALL Export.cpp src/CurlSockets.cpp src/FormFree.cpp + src/CurlFormat.cpp ) if(WIN32) target_compile_definitions(libcurl PRIVATE FD_SETSIZE=1024) @@ -123,7 +124,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() - set(curlTestTopics Utility Url SlistMime Options Handles Transfers MimeCallback Allocators Sockets) + set(curlTestTopics Utility Url SlistMime Options Handles Transfers MimeCallback Allocators Sockets Format FormatStreams) foreach(test_topic IN LISTS curlTestTopics) set(test_name guest_curl_${test_topic}_tests) string(TOLOWER "${test_topic}" test_slug) diff --git a/core/libs/prx/libcurl/Export.cpp b/core/libs/prx/libcurl/Export.cpp index d8adc3035fa3..f6e1be33a8bf 100644 --- a/core/libs/prx/libcurl/Export.cpp +++ b/core/libs/prx/libcurl/Export.cpp @@ -1,4 +1,5 @@ #include "prx/libcurl/src/CurlHost.hpp" +#include "prx/libcurl/src/CurlFormat.hpp" #include "prx/libcurl/src/CurlSockets.hpp" #include "prx/libcurl/include/InventoryExports.hpp" #include "prx/libcurl/include/Api.hpp" @@ -1198,43 +1199,58 @@ void APS5_VABI curl_mime_free_nid_postfix(curl_mime* mime) { int APS5_VABI curl_mvfprintf_nid_postfix(std::FILE* whereto, const char* format, VaList* args) { - NotImplemented_nid_no_patch(__func__); + return CurlFormat::FormatStream(reinterpret_cast(whereto), format, args); } int APS5_VABI curl_mfprintf_nid_postfix(std::FILE* whereto, const char* format, ...) { - NotImplemented_nid_no_patch(__func__); + CURL_ARGS_START(format); + const int result = CurlFormat::FormatStream(reinterpret_cast(whereto), format, args); + CURL_ARGS_END(); + return result; } int APS5_VABI curl_mvsprintf_nid_postfix(char* buffer, const char* format, VaList* args) { - NotImplemented_nid_no_patch(__func__); + return CurlFormat::FormatUnbounded(buffer, format, args); } int APS5_VABI curl_msprintf_nid_postfix(char* buffer, const char* format, ...) { - NotImplemented_nid_no_patch(__func__); + CURL_ARGS_START(format); + const int result = CurlFormat::FormatUnbounded(buffer, format, args); + CURL_ARGS_END(); + return result; } int APS5_VABI curl_mvsnprintf_nid_postfix(char* buffer, size_t maxlength, const char* format, VaList* args) { - NotImplemented_nid_no_patch(__func__); + return CurlFormat::FormatBounded(buffer, maxlength, format, args); } int APS5_VABI curl_msnprintf_nid_postfix(char* buffer, size_t maxlength, const char* format, ...) { - NotImplemented_nid_no_patch(__func__); + CURL_ARGS_START(format); + const int result = CurlFormat::FormatBounded(buffer, maxlength, format, args); + CURL_ARGS_END(); + return result; } int APS5_VABI curl_mvprintf_nid_postfix(const char* format, VaList* args) { - NotImplemented_nid_no_patch(__func__); + return CurlFormat::FormatStream(&_Stdout_nid_postfix, format, args); } int APS5_VABI curl_mprintf_nid_postfix(const char* format, ...) { - NotImplemented_nid_no_patch(__func__); + CURL_ARGS_START(format); + const int result = CurlFormat::FormatStream(&_Stdout_nid_postfix, format, args); + CURL_ARGS_END(); + return result; } char* APS5_VABI curl_mvaprintf_nid_postfix(const char* format, VaList* args) { - NotImplemented_nid_no_patch(__func__); + return CurlFormat::FormatAllocated(format, args); } char* APS5_VABI curl_maprintf_nid_postfix(const char* format, ...) { - NotImplemented_nid_no_patch(__func__); + CURL_ARGS_START(format); + char* const result = CurlFormat::FormatAllocated(format, args); + CURL_ARGS_END(); + return result; } std::int32_t APS5_VABI curl_share_cleanup_nid_postfix(CURLSH* share_handle) { diff --git a/core/libs/prx/libcurl/src/CurlFormat.cpp b/core/libs/prx/libcurl/src/CurlFormat.cpp new file mode 100644 index 000000000000..c2574e077667 --- /dev/null +++ b/core/libs/prx/libcurl/src/CurlFormat.cpp @@ -0,0 +1,734 @@ +// Derived from curl 7.81.0 lib/mprintf.c +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1999 - 2021, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * + * Purpose: + * A merge of Bjorn Reese's format() function and Daniel's dsprintf() + * 1.0. A full blooded printf() clone with full support for $ + * everywhere (parameters, widths and precisions) including variabled + * sized parameters (like doubles, long longs, long doubles and even + * void * in 64-bit architectures). + * + * Current restrictions: + * - Max 128 parameters + * - No 'long double' support. + * + * If you ever want truly portable and good *printf() clones, the project that + * took on from here is named 'Trio' and you find more details on the trio web + * page at https://daniel.haxx.se/projects/trio/ + */ + +#include "prx/libcurl/src/CurlFormat.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/WindowsFormatting.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace CurlFormat { + +namespace { + +constexpr std::int64_t MaxParameters = 128; +constexpr std::size_t WorkSize = 326; +constexpr std::size_t AllocatedLimit = 8000000; +constexpr char LowerDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; +constexpr char UpperDigits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +constexpr char NilText[] = "(nil)"; + +enum class ArgumentType : unsigned char { Unset, Unknown, String, Pointer, Integer, IntegerPointer, Double, Width }; + +enum Flag : unsigned { + FlagSpace = 1u << 0, + FlagShowSign = 1u << 1, + FlagLeft = 1u << 2, + FlagAlt = 1u << 3, + FlagShort = 1u << 4, + FlagLong = 1u << 5, + FlagLongLong = 1u << 6, + FlagLongDouble = 1u << 7, + FlagPadNil = 1u << 8, + FlagUnsigned = 1u << 9, + FlagOctal = 1u << 10, + FlagHex = 1u << 11, + FlagUpper = 1u << 12, + FlagWidth = 1u << 13, + FlagWidthParam = 1u << 14, + FlagPrecision = 1u << 15, + FlagPrecisionParam = 1u << 16, + FlagChar = 1u << 17, + FlagFloatE = 1u << 18, + FlagFloatG = 1u << 19, +}; + +struct Parameter { + ArgumentType type = ArgumentType::Unset; + unsigned flags = 0; + std::int64_t width = 0; + std::int64_t precision = 0; + std::uint64_t data = 0; +}; + +class IOutput { +public: + virtual ~IOutput() = default; + virtual bool Put(unsigned char value) = 0; +}; + +class BoundedOutput final : public IOutput { +public: + BoundedOutput(char* buffer, std::size_t maxLength) : buffer(buffer), maxLength(maxLength) {} + + bool Put(unsigned char value) override { + if (length >= maxLength) return false; + buffer[length++] = static_cast(value); + return true; + } + + std::size_t Length() const { return length; } + +private: + char* buffer; + std::size_t maxLength; + std::size_t length = 0; +}; + +class UnboundedOutput final : public IOutput { +public: + explicit UnboundedOutput(char* buffer) : buffer(buffer) {} + + bool Put(unsigned char value) override { + buffer[length++] = static_cast(value); + return true; + } + + std::size_t Length() const { return length; } + +private: + char* buffer; + std::size_t length = 0; +}; + +class StreamOutput final : public IOutput { +public: + explicit StreamOutput(FileStream* stream) : stream(stream) {} + bool Put(unsigned char value) override { + return fputc_nid_postfix(value, stream) != -1; + } + +private: + FileStream* stream; +}; + +class AllocatedOutput final : public IOutput { +public: + bool Put(unsigned char value) override { + if (text.size() + 2 > AllocatedLimit) { + failed = true; + return false; + } + text.push_back(static_cast(value)); + return true; + } + + bool Failed() const { return failed; } + const std::string& Text() const { return text; } + +private: + std::string text; + bool failed = false; +}; + +bool IsDigit(char value) { + return value >= '0' && value <= '9'; +} + +std::int64_t DollarString(const char* input, const char** end) { + int number = 0; + while (IsDigit(*input)) { + if (number < MaxParameters) { + number *= 10; + number += *input - '0'; + } + ++input; + } + if (number <= MaxParameters && *input == '$') { + *end = input + 1; + return number; + } + return 0; +} + +bool IsQualifier(char value) { + switch (value) { + case '-': case '+': case ' ': case '#': case '.': + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case 'h': case 'l': case 'L': case 'z': case 'q': + case '*': case 'O': + return true; + default: + return false; + } +} + +std::int64_t ParseDecimal(const char* text, const char** end) { + char* stop = nullptr; + const long long value = std::strtoll(text, &stop, 10); + *end = stop; + return value; +} + +std::int64_t Signed(std::uint64_t value) { + return static_cast(value); +} + +class Formatter { +public: + Formatter(IOutput& output, const void* args) : output(output), arguments(args) {} + + int Run(const char* format) { + if (!collect(format)) return -1; + std::size_t end = 0; + std::int64_t paramNum = 0; + const char* f = format; + while (*f != '\0') { + if (*f != '%') { + do { + if (!emit(*f)) return done; + } while (*++f && *f != '%'); + continue; + } + ++f; + if (*f == '%') { + ++f; + if (!emit('%')) return done; + continue; + } + std::int64_t param = DollarString(f, &f); + if (!param) param = paramNum; + else --param; + ++paramNum; + Parameter& p = referenced(param); + std::int64_t width; + if (p.flags & FlagWidthParam) { + width = Signed(referenced(p.width).data); + ++paramNum; + if (width < 0) { + width = -width; + p.flags |= FlagLeft; + p.flags &= ~FlagPadNil; + } + } else { + width = p.width; + } + std::int64_t precision; + if (p.flags & FlagPrecisionParam) { + precision = Signed(referenced(p.precision).data); + ++paramNum; + if (precision < 0) precision = -1; + } else if (p.flags & FlagPrecision) { + precision = p.precision; + } else { + precision = -1; + } + if (!convert(p, width, precision)) return done; + if (end >= ends.size()) throw std::logic_error("curl format conversion has no recorded end"); + f = ends[end++]; + } + return done; + } + +private: + IOutput& output; + LibcDetail::FormatArguments arguments; + std::array parameters{}; + std::vector ends; + int done = 0; + + bool emit(char value) { + if (!output.Put(static_cast(value))) return false; + ++done; + return true; + } + + Parameter& referenced(std::int64_t index) { + if (index < 0 || index >= MaxParameters) throw std::out_of_range("curl format references an argument position outside its 128 parameters"); + Parameter& parameter = parameters[static_cast(index)]; + if (parameter.type == ArgumentType::Unset) throw std::invalid_argument("curl format references an argument position no conversion describes"); + return parameter; + } + + bool collect(const char* format) { + const char* fmt = format; + std::int64_t paramNum = 0; + std::int64_t maxParam = 0; + while (*fmt) { + if (*fmt++ != '%') continue; + if (*fmt == '%') { + ++fmt; + continue; + } + unsigned flags = 0; + ++paramNum; + std::int64_t thisParam = DollarString(fmt, &fmt); + if (thisParam == 0) thisParam = paramNum; + if (thisParam > maxParam) maxParam = thisParam; + std::int64_t width = 0; + std::int64_t precision = 0; + while (IsQualifier(*fmt)) { + switch (*fmt++) { + case ' ': + flags |= FlagSpace; + break; + case '+': + flags |= FlagShowSign; + break; + case '-': + flags |= FlagLeft; + flags &= ~FlagPadNil; + break; + case '#': + flags |= FlagAlt; + break; + case '.': + if (*fmt == '*') { + flags |= FlagPrecisionParam; + ++fmt; + ++paramNum; + const std::int64_t position = DollarString(fmt, &fmt); + precision = position ? position : paramNum; + if (precision > maxParam) maxParam = precision; + } else { + flags |= FlagPrecision; + precision = ParseDecimal(fmt, &fmt); + } + break; + case 'h': + flags |= FlagShort; + break; + case 'l': + if (flags & FlagLong) flags |= FlagLongLong; + else flags |= FlagLong; + break; + case 'L': + flags |= FlagLongDouble; + break; + case 'q': + flags |= FlagLongLong; + break; + case 'z': + case 'O': + flags |= FlagLong; + break; + case '0': + if (!(flags & FlagLeft)) flags |= FlagPadNil; + [[fallthrough]]; + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + flags |= FlagWidth; + width = ParseDecimal(fmt - 1, &fmt); + break; + case '*': { + flags |= FlagWidthParam; + ++paramNum; + const std::int64_t position = DollarString(fmt, &fmt); + width = position ? position : paramNum; + if (width > maxParam) maxParam = width; + break; + } + default: + break; + } + } + const std::int64_t index = thisParam - 1; + if (index < 0 || index >= MaxParameters) return false; + Parameter& entry = parameters[static_cast(index)]; + switch (*fmt) { + case 'S': + flags |= FlagAlt; + [[fallthrough]]; + case 's': + entry.type = ArgumentType::String; + break; + case 'n': + entry.type = ArgumentType::IntegerPointer; + break; + case 'p': + entry.type = ArgumentType::Pointer; + break; + case 'd': case 'i': + entry.type = ArgumentType::Integer; + break; + case 'u': + entry.type = ArgumentType::Integer; + flags |= FlagUnsigned; + break; + case 'o': + entry.type = ArgumentType::Integer; + flags |= FlagOctal; + break; + case 'x': + entry.type = ArgumentType::Integer; + flags |= FlagHex | FlagUnsigned; + break; + case 'X': + entry.type = ArgumentType::Integer; + flags |= FlagHex | FlagUpper | FlagUnsigned; + break; + case 'c': + entry.type = ArgumentType::Integer; + flags |= FlagChar; + break; + case 'f': + entry.type = ArgumentType::Double; + break; + case 'e': + entry.type = ArgumentType::Double; + flags |= FlagFloatE; + break; + case 'E': + entry.type = ArgumentType::Double; + flags |= FlagFloatE | FlagUpper; + break; + case 'g': + entry.type = ArgumentType::Double; + flags |= FlagFloatG; + break; + case 'G': + entry.type = ArgumentType::Double; + flags |= FlagFloatG | FlagUpper; + break; + default: + entry.type = ArgumentType::Unknown; + break; + } + entry.flags = flags; + entry.width = width; + entry.precision = precision; + if (flags & FlagWidthParam) { + const std::int64_t k = width - 1; + if (k < 0 || k >= MaxParameters) return false; + entry.width = k; + markWidth(parameters[static_cast(k)]); + } + if (flags & FlagPrecisionParam) { + const std::int64_t k = precision - 1; + if (k < 0 || k >= MaxParameters) return false; + entry.precision = k; + markWidth(parameters[static_cast(k)]); + } + if (ends.size() == static_cast(MaxParameters)) throw std::length_error("curl format has more than 128 conversions"); + ends.push_back(fmt + (*fmt == '\0' ? 0 : 1)); + } + for (std::int64_t i = 0; i < maxParam; ++i) { + Parameter& entry = parameters[static_cast(i)]; + if (entry.type == ArgumentType::Unset) throw std::invalid_argument("curl format leaves an argument position unused"); + if (entry.flags & FlagWidthParam) parameters[static_cast(entry.width)].data = static_cast(static_cast(arguments.Next())); + if (entry.flags & FlagPrecisionParam) parameters[static_cast(entry.precision)].data = static_cast(static_cast(arguments.Next())); + switch (entry.type) { + case ArgumentType::String: + case ArgumentType::IntegerPointer: + case ArgumentType::Unknown: + case ArgumentType::Pointer: + entry.data = arguments.Next(); + break; + case ArgumentType::Integer: + if (entry.flags & (FlagLongLong | FlagLong)) entry.data = arguments.Next(); + else if (entry.flags & FlagUnsigned) entry.data = arguments.Next(); + else entry.data = static_cast(static_cast(arguments.Next())); + break; + case ArgumentType::Double: { + const double value = arguments.Next(); + std::memcpy(&entry.data, &value, sizeof(value)); + break; + } + case ArgumentType::Width: + entry.type = ArgumentType::Integer; + break; + default: + break; + } + } + return true; + } + + static void markWidth(Parameter& parameter) { + parameter.type = ArgumentType::Width; + parameter.flags = 0; + parameter.width = 0; + parameter.precision = 0; + } + + bool convert(Parameter& p, std::int64_t width, std::int64_t precision) { + const bool alt = (p.flags & FlagAlt) != 0; + switch (p.type) { + case ArgumentType::Integer: + return integer(p, width, precision, alt); + case ArgumentType::String: + return text(p, width, precision); + case ArgumentType::Pointer: + return pointer(p, width, precision); + case ArgumentType::Double: + return floating(p); + case ArgumentType::IntegerPointer: + count(p); + return true; + default: + return true; + } + } + + bool integer(const Parameter& p, std::int64_t width, std::int64_t precision, bool alt) { + std::uint64_t num = p.data; + if (p.flags & FlagChar) { + if (!(p.flags & FlagLeft)) + while (--width > 0) + if (!emit(' ')) return false; + if (!emit(static_cast(num))) return false; + if (p.flags & FlagLeft) + while (--width > 0) + if (!emit(' ')) return false; + return true; + } + if (p.flags & FlagOctal) return number(p, num, 8, false, alt, LowerDigits, width, precision); + if (p.flags & FlagHex) return number(p, num, 16, false, alt, (p.flags & FlagUpper) ? UpperDigits : LowerDigits, width, precision); + if (p.flags & FlagUnsigned) return number(p, num, 10, false, alt, LowerDigits, width, precision); + const bool negative = Signed(p.data) < 0; + if (negative) { + std::int64_t signedNum = Signed(p.data) + 1; + signedNum = -signedNum; + num = static_cast(signedNum); + num += 1; + } + return number(p, num, 10, negative, alt, LowerDigits, width, precision); + } + + bool number(const Parameter& p, std::uint64_t num, unsigned base, bool negative, bool alt, const char* digits, std::int64_t width, std::int64_t precision) { + std::array work{}; + const std::ptrdiff_t workEnd = static_cast(WorkSize) - 2; + std::ptrdiff_t w = workEnd; + if (precision == -1) precision = 1; + while (num > 0) { + work[static_cast(w--)] = digits[num % base]; + num /= base; + } + width -= workEnd - w; + precision -= workEnd - w; + if (alt && base == 8 && precision <= 0) { + work[static_cast(w--)] = '0'; + --width; + } + if (precision > 0) { + width -= precision; + while (precision-- > 0 && w >= 0) work[static_cast(w--)] = '0'; + } + if (alt && base == 16) width -= 2; + if (negative || (p.flags & FlagShowSign) || (p.flags & FlagSpace)) --width; + if (!(p.flags & FlagLeft) && !(p.flags & FlagPadNil)) + while (width-- > 0) + if (!emit(' ')) return false; + if (negative) { + if (!emit('-')) return false; + } else if (p.flags & FlagShowSign) { + if (!emit('+')) return false; + } else if (p.flags & FlagSpace) { + if (!emit(' ')) return false; + } + if (alt && base == 16) { + if (!emit('0')) return false; + if (!emit((p.flags & FlagUpper) ? 'X' : 'x')) return false; + } + if (!(p.flags & FlagLeft) && (p.flags & FlagPadNil)) + while (width-- > 0) + if (!emit('0')) return false; + while (++w <= workEnd) + if (!emit(work[static_cast(w)])) return false; + if (p.flags & FlagLeft) + while (width-- > 0) + if (!emit(' ')) return false; + return true; + } + + bool text(Parameter& p, std::int64_t width, std::int64_t precision) { + const char* str = reinterpret_cast(p.data); + std::size_t length; + if (!str) { + if (precision == -1 || precision >= static_cast(sizeof(NilText)) - 1) { + str = NilText; + length = sizeof(NilText) - 1; + p.flags &= ~FlagAlt; + } else { + str = ""; + length = 0; + } + } else if (precision != -1) { + length = static_cast(precision); + } else { + length = std::strlen(str); + } + constexpr auto longMax = std::numeric_limits::max(); + width -= length > static_cast(longMax) ? longMax : static_cast(length); + if (p.flags & FlagAlt) + if (!emit('"')) return false; + if (!(p.flags & FlagLeft)) + while (width-- > 0) + if (!emit(' ')) return false; + for (; length && *str; --length) + if (!emit(*str++)) return false; + if (p.flags & FlagLeft) + while (width-- > 0) + if (!emit(' ')) return false; + if (p.flags & FlagAlt) + if (!emit('"')) return false; + return true; + } + + bool pointer(const Parameter& p, std::int64_t width, std::int64_t precision) { + if (p.data) return number(p, p.data, 16, false, true, (p.flags & FlagUpper) ? UpperDigits : LowerDigits, width, precision); + width -= static_cast(sizeof(NilText) - 1); + if (p.flags & FlagLeft) + while (width-- > 0) + if (!emit(' ')) return false; + for (const char* point = NilText; *point != '\0'; ++point) + if (!emit(*point)) return false; + if (!(p.flags & FlagLeft)) + while (width-- > 0) + if (!emit(' ')) return false; + return true; + } + + bool floating(const Parameter& p) { + std::array formatBuffer{}; + formatBuffer[0] = '%'; + std::size_t position = 1; + std::size_t left = formatBuffer.size() - 1; + std::int64_t width = -1; + if (p.flags & FlagWidth) width = p.width; + else if (p.flags & FlagWidthParam) width = Signed(referenced(p.width).data); + std::int64_t precision = -1; + if (p.flags & FlagPrecision) precision = p.precision; + else if (p.flags & FlagPrecisionParam) precision = Signed(referenced(p.precision).data); + if (p.flags & FlagLeft) formatBuffer[position++] = '-'; + if (p.flags & FlagShowSign) formatBuffer[position++] = '+'; + if (p.flags & FlagSpace) formatBuffer[position++] = ' '; + if (p.flags & FlagAlt) formatBuffer[position++] = '#'; + left -= position - 1; + if (width >= 0) { + if (width >= static_cast(WorkSize)) width = static_cast(WorkSize) - 1; + const int length = std::snprintf(&formatBuffer[position], left, "%lld", static_cast(width)); + position += static_cast(length); + left -= static_cast(length); + } + double value; + std::memcpy(&value, &p.data, sizeof(value)); + if (precision >= 0) { + std::size_t maxPrecision = WorkSize - 2; + double magnitude = value; + if (width > 0 && precision <= width) maxPrecision -= static_cast(width); + while (magnitude >= 10.0) { + magnitude /= 10; + --maxPrecision; + } + if (precision > static_cast(maxPrecision)) precision = static_cast(maxPrecision) - 1; + if (precision < 0) precision = 0; + const int length = std::snprintf(&formatBuffer[position], left, ".%lld", static_cast(precision)); + position += static_cast(length); + } + if (p.flags & FlagLong) formatBuffer[position++] = 'l'; + if (p.flags & FlagFloatE) formatBuffer[position++] = (p.flags & FlagUpper) ? 'E' : 'e'; + else if (p.flags & FlagFloatG) formatBuffer[position++] = (p.flags & FlagUpper) ? 'G' : 'g'; + else formatBuffer[position++] = 'f'; + formatBuffer[position] = '\0'; + std::array work{}; + const int written = snprintf_nid_postfix(work.data(), work.size(), formatBuffer.data(), value); + if (written < 0 || static_cast(written) >= work.size()) throw std::length_error("curl floating-point conversion exceeds its 326-byte work buffer"); + for (const char* character = work.data(); *character; ++character) + if (!emit(*character)) return false; + return true; + } + + void count(const Parameter& p) { + void* target = reinterpret_cast(p.data); + bool written; + if (p.flags & (FlagLongLong | FlagLong)) { + const std::int64_t value = done; + written = GuestCopyOut_nid_no_patch(target, &value, sizeof(value)); + } else if (!(p.flags & FlagShort)) { + const std::int32_t value = done; + written = GuestCopyOut_nid_no_patch(target, &value, sizeof(value)); + } else { + const auto value = static_cast(done); + written = GuestCopyOut_nid_no_patch(target, &value, sizeof(value)); + } + if (!written) throw std::invalid_argument("curl %n destination is not writable guest memory"); + } +}; + +} + +int FormatBounded(char* buffer, std::size_t maxLength, const char* format, const void* args) { + BoundedOutput output(buffer, maxLength); + int result = Formatter(output, args).Run(format); + if (result != -1 && maxLength) { + if (output.Length() == maxLength) { + buffer[maxLength - 1] = '\0'; + --result; + } else { + buffer[output.Length()] = '\0'; + } + } + return result; +} + +int FormatUnbounded(char* buffer, const char* format, const void* args) { + UnboundedOutput output(buffer); + const int result = Formatter(output, args).Run(format); + buffer[output.Length()] = '\0'; + return result; +} + +char* FormatAllocated(const char* format, const void* args) { + AllocatedOutput output; + const int result = Formatter(output, args).Run(format); + if (result == -1 || output.Failed()) return nullptr; + const std::string& text = output.Text(); + auto* copy = static_cast(malloc_nid_postfix(text.size() + 1)); + if (!copy) return nullptr; + std::memcpy(copy, text.data(), text.size()); + copy[text.size()] = '\0'; + return copy; +} + +int FormatStream(FileStream* stream, const char* format, const void* args) { + StreamOutput output(stream); + return Formatter(output, args).Run(format); +} + +} diff --git a/core/libs/prx/libcurl/src/CurlFormat.hpp b/core/libs/prx/libcurl/src/CurlFormat.hpp new file mode 100644 index 000000000000..1a957ece361f --- /dev/null +++ b/core/libs/prx/libcurl/src/CurlFormat.hpp @@ -0,0 +1,17 @@ +#ifndef CORE_LIBS_PRX_LIBCURL_SRC_CURLFORMAT_HPP +#define CORE_LIBS_PRX_LIBCURL_SRC_CURLFORMAT_HPP + +#include + +class FileStream; + +namespace CurlFormat { + +int FormatBounded(char* buffer, std::size_t maxLength, const char* format, const void* args); +int FormatUnbounded(char* buffer, const char* format, const void* args); +char* FormatAllocated(const char* format, const void* args); +int FormatStream(FileStream* stream, const char* format, const void* args); + +} + +#endif diff --git a/core/libs/prx/libcurl/tests/CurlFormat.cpp b/core/libs/prx/libcurl/tests/CurlFormat.cpp new file mode 100644 index 000000000000..a4cdf062edf0 --- /dev/null +++ b/core/libs/prx/libcurl/tests/CurlFormat.cpp @@ -0,0 +1,175 @@ +#include "prx/libcurl/src/CurlHost.hpp" +#include "prx/libcurl/libcurl.hpp" +#include "prx/libc/include/ApplicationHeap.hpp" +#include +#include +#include +#include +#include + +#if defined(__clang__) && !defined(_WIN32) +#define __builtin_sysv_va_list va_list +#define __builtin_sysv_va_start va_start +#define __builtin_sysv_va_end va_end +#endif + +static void Require(bool condition) { + if (!condition) std::abort(); +} + +static bool Equals(const char* actual, const char* expected) { + return actual != nullptr && std::strcmp(actual, expected) == 0; +} + +static int APS5_VABI BoundedList(char* buffer, size_t size, const char* format, ...) { + __builtin_sysv_va_list args; + __builtin_sysv_va_start(args, format); + VaList list; + std::memcpy(&list, args, sizeof(list)); + const VaList original = list; + const int result = curl_mvsnprintf_nid_postfix(buffer, size, format, &list); + Require(std::memcmp(&list, &original, sizeof(list)) == 0); + __builtin_sysv_va_end(args); + return result; +} + +static int APS5_VABI UnboundedList(char* buffer, const char* format, ...) { + __builtin_sysv_va_list args; + __builtin_sysv_va_start(args, format); + VaList list; + std::memcpy(&list, args, sizeof(list)); + const int result = curl_mvsprintf_nid_postfix(buffer, format, &list); + __builtin_sysv_va_end(args); + return result; +} + +static char* APS5_VABI AllocatedList(const char* format, ...) { + __builtin_sysv_va_list args; + __builtin_sysv_va_start(args, format); + VaList list; + std::memcpy(&list, args, sizeof(list)); + char* result = curl_mvaprintf_nid_postfix(format, &list); + __builtin_sysv_va_end(args); + return result; +} + +static void TestIntegers() { + char buffer[128]; + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%d|%5d|%-5d|%05d|%+d|% d", 42, 42, 42, 42, 42, 42) == 28); + Require(Equals(buffer, "42| 42|42 |00042|+42| 42")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%ld %lu %lld %zu %lx %qd", std::int64_t{-5000000000}, std::uint64_t{5000000000}, std::int64_t{-9000000000}, std::uint64_t{6000000000}, std::uint64_t{0x123456789}, std::int64_t{7000000000}) == 66); + Require(Equals(buffer, "-5000000000 5000000000 -9000000000 6000000000 123456789 7000000000")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%d %u %x %X %#x %#o %o", std::int64_t{0x100000005}, -1, -1, 255, 255, 8, 8) == 36); + Require(Equals(buffer, "5 4294967295 ffffffff FF 0xff 010 10")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%.4d|%8.3d|%-+6d|%d", 7, -7, 7, std::int64_t{-2147483648}) == 32); + Require(Equals(buffer, "0007| -007|+7 |-2147483648")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%c|%3c|%-3c|", 'A', 'B', 'C') == 10); + Require(Equals(buffer, "A| B|C |")); +} + +static void TestStringsAndPointers() { + char buffer[128]; + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%s|%.3s|%8s|%-8s|%s|%.2s|%S", "hello", "hello", "hi", "hi", static_cast(nullptr), static_cast(nullptr), "q") == 38); + Require(Equals(buffer, "hello|hel| hi|hi |(nil)||\"q\"")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%p|%p|%8p|", static_cast(nullptr), reinterpret_cast(std::uintptr_t{0x1234}), static_cast(nullptr)) == 22); + Require(Equals(buffer, "(nil)|0x1234|(nil) |")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "100%% %y%d", static_cast(nullptr), 5) == 6); + Require(Equals(buffer, "100% 5")); +} + +static void TestParameters() { + char buffer[128]; + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%2$s %1$s", "a", "b") == 3); + Require(Equals(buffer, "b a")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%*d|%-*d|%.*d|%*d|", 4, 7, 4, 7, 3, 7, -4, 7) == 19); + Require(Equals(buffer, " 7|7 |007|7 |")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%2$*1$d|", 5, 9) == 6); + Require(Equals(buffer, " 9|")); +} + +static void TestFloatingPoint() { + char buffer[128]; + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%f|%.2f|%e|%g|%8.3f|%-8.1f|%+E|%05.1f", 1.5, 3.14159, 12345.678, 0.0001, 2.5, 2.5, 1.0, 2.5) == 71); + Require(Equals(buffer, "1.500000|3.14|1.234568e+04|0.0001| 2.500|2.5 |+1.000000E+00| 2.5")); + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "%d %f %d", 1, 0.5, 2) == 12); + Require(Equals(buffer, "1 0.500000 2")); +} + +static void TestCounts() { + char buffer[64]; + std::int32_t count = -1; + std::int64_t wide = -1; + std::int16_t narrow = -1; + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), "abc%n%sxy%ln%hn", &count, "de", &wide, &narrow) == 7); + Require(Equals(buffer, "abcdexy")); + Require(count == 3); + Require(wide == 7); + Require(narrow == 7); +} + +static void TestBounds() { + char buffer[16]; + Require(curl_msnprintf_nid_postfix(buffer, 5, "%s", "abcdefgh") == 4); + Require(Equals(buffer, "abcd")); + Require(curl_msnprintf_nid_postfix(buffer, 4, "abc") == 3); + Require(Equals(buffer, "abc")); + buffer[0] = 'Z'; + Require(curl_msnprintf_nid_postfix(buffer, 0, "abc") == 0); + Require(buffer[0] == 'Z'); + std::int32_t count = -1; + Require(curl_msnprintf_nid_postfix(buffer, 3, "abcdef%n", &count) == 2); + Require(Equals(buffer, "ab")); + Require(count == -1); + std::string tooMany; + for (int index = 0; index < 129; ++index) tooMany += "%d"; + buffer[0] = 'Z'; + Require(curl_msnprintf_nid_postfix(buffer, sizeof(buffer), tooMany.c_str()) == -1); + Require(buffer[0] == 'Z'); + Require(curl_msprintf_nid_postfix(buffer, tooMany.c_str()) == -1); + Require(buffer[0] == '\0'); + Require(curl_maprintf_nid_postfix(tooMany.c_str()) == nullptr); +} + +static void TestLists() { + char buffer[64]; + Require(BoundedList(buffer, sizeof(buffer), "%s=%ld", "key", std::int64_t{-8000000000}) == 15); + Require(Equals(buffer, "key=-8000000000")); + Require(BoundedList(buffer, 4, "%d", 123456) == 3); + Require(Equals(buffer, "123")); + Require(UnboundedList(buffer, "%03d:%s", 5, "ok") == 6); + Require(Equals(buffer, "005:ok")); + char* text = AllocatedList("%s-%lu", "id", std::uint64_t{10000000000}); + Require(Equals(text, "id-10000000000")); + curl_free(text); +} + +static void TestUnboundedAndAllocated() { + char buffer[64]; + std::memset(buffer, 'x', sizeof(buffer)); + Require(curl_msprintf_nid_postfix(buffer, "%d-%s", 7, "x") == 3); + Require(Equals(buffer, "7-x")); + char* text = curl_maprintf_nid_postfix("%s=%ld", "k", std::int64_t{9000000000}); + Require(Equals(text, "k=9000000000")); + curl_free(text); + char* empty = curl_maprintf_nid_postfix(""); + Require(Equals(empty, "")); + curl_free(empty); + std::string large(7999998, 'a'); + char* fits = curl_maprintf_nid_postfix("%s%c", large.c_str(), 'b'); + Require(fits != nullptr && std::strlen(fits) == 7999999); + curl_free(fits); + Require(curl_maprintf_nid_postfix("%s%s", large.c_str(), "bc") == nullptr); +} + +int main() { + ApplicationHeapInitialize_nid_no_patch(ApplicationEmptyProcessParameters_nid_no_patch()); + TestIntegers(); + TestStringsAndPointers(); + TestParameters(); + TestFloatingPoint(); + TestCounts(); + TestBounds(); + TestLists(); + TestUnboundedAndAllocated(); + return 0; +} diff --git a/core/libs/prx/libcurl/tests/CurlFormatStreams.cpp b/core/libs/prx/libcurl/tests/CurlFormatStreams.cpp new file mode 100644 index 000000000000..22090a7ea884 --- /dev/null +++ b/core/libs/prx/libcurl/tests/CurlFormatStreams.cpp @@ -0,0 +1,83 @@ +#include "prx/libcurl/src/CurlHost.hpp" +#include "prx/libcurl/libcurl.hpp" +#include "prx/libc/include/ApplicationHeap.hpp" +#include "prx/libc/include/Api.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__clang__) && !defined(_WIN32) +#define __builtin_sysv_va_list va_list +#define __builtin_sysv_va_start va_start +#define __builtin_sysv_va_end va_end +#endif + +static void Require(bool value, std::source_location location = std::source_location::current()) { + if (!value) { + std::fprintf(stderr, "failure at %u\n", location.line()); + std::exit(1); + } +} + +static int APS5_VABI FormatStream(FileStream* stream, const char* format, ...) { + __builtin_sysv_va_list args; + __builtin_sysv_va_start(args, format); + const int result = curl_mvfprintf_nid_postfix(reinterpret_cast(stream), format, reinterpret_cast(args)); + __builtin_sysv_va_end(args); + return result; +} + +static int APS5_VABI FormatStandardOutput(const char* format, ...) { + __builtin_sysv_va_list args; + __builtin_sysv_va_start(args, format); + const int result = curl_mvprintf_nid_postfix(format, reinterpret_cast(args)); + __builtin_sysv_va_end(args); + return result; +} + +static std::string ReadAll(const std::string& path) { + std::ifstream input(path, std::ios::binary); + return std::string((std::istreambuf_iterator(input)), std::istreambuf_iterator()); +} + +static void TestFileStreams() { + const std::string path = "curl_format_streams.tmp"; + auto* stream = fopen_nid_postfix(path.c_str(), "w"); + Require(stream != nullptr); + Require(curl_mfprintf_nid_postfix(reinterpret_cast(stream), "%s %d|%-4s|%2$d;", "one", 1, "x") == 13); + Require(FormatStream(stream, "%s %#x %p", "two", 255, static_cast(nullptr)) == 14); + std::string tooMany; + for (int index = 0; index < 129; ++index) tooMany += "%d"; + Require(curl_mfprintf_nid_postfix(reinterpret_cast(stream), tooMany.c_str()) == -1); + Require(fclose_nid_postfix(stream) == 0); + Require(ReadAll(path) == "one 1|x |1;two 0xff (nil)"); + + stream = fopen_nid_postfix(path.c_str(), "r"); + Require(stream != nullptr); + Require(curl_mfprintf_nid_postfix(reinterpret_cast(stream), "abc") == 0); + Require(fclose_nid_postfix(stream) == 0); + std::filesystem::remove(path); +} + +static void TestStandardOutput() { + const std::string path = "curl_format_stdout.tmp"; + Require(freopen_nid_postfix(path.c_str(), "w", &_Stdout_nid_postfix) == &_Stdout_nid_postfix); + Require(curl_mprintf_nid_postfix("%s=%03d;", "mprintf", 7) == 12); + Require(FormatStandardOutput("%c%c", 'o', 'k') == 2); + Require(fflush_nid_postfix(&_Stdout_nid_postfix) == 0); + Require(ReadAll(path) == "mprintf=007;ok"); + Require(fclose_nid_postfix(&_Stdout_nid_postfix) == 0); + std::filesystem::remove(path); +} + +int main() { + ApplicationHeapInitialize_nid_no_patch(ApplicationEmptyProcessParameters_nid_no_patch()); + TestFileStreams(); + TestStandardOutput(); + return 0; +} diff --git a/docs/dev/debt/libcurl.md b/docs/dev/debt/libcurl.md index 3b27a36e36bd..db211497809c 100644 --- a/docs/dev/debt/libcurl.md +++ b/docs/dev/debt/libcurl.md @@ -16,11 +16,18 @@ - [Default stdio streams](../../../core/libs/prx/libcurl/Export.cpp) - with the default callbacks, a NULL `WRITEDATA` ends the transfer with `CURLE_WRITE_ERROR` and a NULL `READDATA` with `CURLE_ABORTED_BY_CALLBACK`, where libcurl would pass NULL to `fwrite` or `fread`. A rewind of the default input returns `CURL_SEEKFUNC_CANTSEEK` when guest `fseek` fails or the stream is NULL; a rewind of a `/dev/random` or `/dev/urandom` stream throws `std::runtime_error` through libcurl's frames. Native `Curl_readrewind` identifies its default input by comparing the read function to host fread. The guest default read trampoline needs an internal seek callback instead; successful rewinds use guest fseek, but a failed rewind cannot reproduce the native diagnostic path through that callback. - [Transfer scope](../../../core/libs/prx/libcurl/Export.cpp) - HTTP/HTTPS transfers, HSTS callbacks, disabled protocol callbacks and asynchronous native writes into guest buffers remain unverified. File URLs use the host filesystem and Windows file URL normalization rather than a guest path namespace. Verbose bytes use guest fwrite; the built-in progress meter writes the native stream underlying STDERR, without guest FileStream state updates. The standalone harness substitutes guest stdio operations and does not verify arena protection or full libc integration. - [`curl_formadd`](../../../core/libs/prx/libcurl/Export.cpp) - the guest node layout is the unverified LP64 mirror of curl 7.81.0's `struct curl_httppost`. On LLP64 hosts a `CURLFORM_NAMELENGTH` or `BUFFERLENGTH` value that does not fit a host `long` throws `std::out_of_range`, like the Guest long entry above. Guest varargs and arrays are passed to curl 7.81.0's [FormAdd](https://github.com/curl/curl/blob/801bd5138ce31aa0d906fa4e2eabfc599d74e793/lib/formdata.c#L203-L690) on an empty list; it allocates names, contents and nodes through the guest heap of the Allocator entry. The nodes it adds are copied into guest nodes and linked as `AddHttpPost` does: after `*last_post`, or as `*httppost` when the list is empty. A null `CURLFORM_ARRAY` returns the error of an earlier option or `CURL_FORMADD_NULL`, with nothing added. +- [Formatting](../../../core/libs/prx/libcurl/src/CurlFormat.cpp) - `curl_m[v]snprintf`, `curl_m[v]sprintf`, `curl_m[v]aprintf`, `curl_m[v]fprintf` and `curl_m[v]printf` follow `lib/mprintf.c` of curl 7.81.0 with LP64 argument sizes and without the Windows `I32` and `I64` qualifiers, and format floating-point conversions through the guest `snprintf` instead of the console `sprintf`. Their digits are those of the `%e, %f and %g` entry of [libc](libc.md), which the console's curl also gets from `libc.prx`, so they differ from a host build of curl on exact ties and past 17 significant digits (`%.0f` of 2.5 is `3` here and `2` in a Windows host build). Formats whose behaviour there is undefined throw instead: an argument position no conversion describes, more than 128 conversions, a floating-point result longer than the 326-byte work buffer and a `%n` destination that is not writable guest memory. Console output is unverified. Labels: console, tested - [`curl_formfree`](../../../core/libs/prx/libcurl/src/FormFree.cpp) - the guest node layout is the unverified LP64 mirror of curl 7.81.0's `struct curl_httppost`, and nodes are released through the guest heap described under Allocator. Adapted from [lib/formdata.c](https://github.com/curl/curl/blob/801bd5138ce31aa0d906fa4e2eabfc599d74e793/lib/formdata.c#L746-L771): it frees each node of the `next` chain after its `more` chain, keeping names marked `CURL_HTTPPOST_PTRNAME` and contents marked `PTRCONTENTS`, `BUFFER` or `CALLBACK`. ### Unimplemented exports - [`curl_formget`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: LP64 form nodes and length options are not translated to LLP64 host forms. +- [`curl_global_init_mem`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: Allocator callback ownership across repeated initialization and cleanup is not adapted exactly. +- [`curl_mime_data_cb`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: Curl_mime_duppart copies the same callback argument and free function without a duplication hook. Per-part guest callback contexts cannot be copied and freed with exact ownership across duplicates; no adapter is installed. +- [`curl_multi_assign`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: The guest registry lacks reverse lookup and borrowed-owner installation for curl-owned sockets; see Socket ownership above. +- [`curl_multi_fdset`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: The guest registry lacks reverse lookup and borrowed-owner installation for curl-owned sockets; see Socket ownership above. +- [`curl_multi_socket`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: The guest registry lacks reverse lookup and borrowed-owner installation for curl-owned sockets; see Socket ownership above. +- [`curl_multi_socket_action`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: The guest registry lacks reverse lookup and borrowed-owner installation for curl-owned sockets; see Socket ownership above. - [`curl_maprintf`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: SysV variadic formatting with LP64 long and %ln writes and guest FILE streams has no exact adapter. - [`curl_mfprintf`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: SysV variadic formatting with LP64 long and %ln writes and guest FILE streams has no exact adapter. - [`curl_mprintf`](../../../core/libs/prx/libcurl/Export.cpp) - throws through `NotImplemented_nid_no_patch`: SysV variadic formatting with LP64 long and %ln writes and guest FILE streams has no exact adapter.