Index: llvm/CMakeLists.txt =================================================================== --- llvm/CMakeLists.txt +++ llvm/CMakeLists.txt @@ -519,6 +519,8 @@ set(LLVM_ENABLE_CURL "OFF" CACHE STRING "Use libcurl for the HTTP client if available. Can be ON, OFF, or FORCE_ON") +set(LLVM_ENABLE_ICONV "ON" CACHE STRING "Use iconv for character set conversion if available. Can be ON, OFF, or FORCE_ON") + set(LLVM_ENABLE_HTTPLIB "OFF" CACHE STRING "Use cpp-httplib HTTP server library if available. Can be ON, OFF, or FORCE_ON") set(LLVM_Z3_INSTALL_DIR "" CACHE STRING "Install directory of the Z3 solver.") Index: llvm/cmake/config-ix.cmake =================================================================== --- llvm/cmake/config-ix.cmake +++ llvm/cmake/config-ix.cmake @@ -251,6 +251,28 @@ endif() endif() +# Check for iconv. +if(LLVM_ENABLE_ICONV) + if(LLVM_ENABLE_ICONV STREQUAL FORCE_ON) + find_package(Iconv REQUIRED) + elseif(NOT LLVM_USE_SANITIZER MATCHES "Memory.*") + find_package(Iconv) + endif() + if(Iconv_FOUND) + # Check if iconv we found is usable; for example, we may have found a 32-bit + # library on a 64-bit system which would result in a link-time failure. + cmake_push_check_state() + list(APPEND CMAKE_REQUIRED_INCLUDES ${Iconv_INCLUDE_DIRS}) + list(APPEND CMAKE_REQUIRED_LIBRARIES ${Iconv_LIBRARIES}) + check_symbol_exists(iconv_open iconv.h HAVE_ICONV) + cmake_pop_check_state() + if(LLVM_ENABLE_ICONV STREQUAL FORCE_ON AND NOT HAVE_ICONV) + message(FATAL_ERROR "Failed to configure iconv") + endif() + endif() + set(LLVM_ENABLE_ICONV "${HAVE_ICONV}") +endif() + # function checks check_symbol_exists(arc4random "stdlib.h" HAVE_DECL_ARC4RANDOM) find_package(Backtrace) Index: llvm/cmake/modules/LLVMConfig.cmake.in =================================================================== --- llvm/cmake/modules/LLVMConfig.cmake.in +++ llvm/cmake/modules/LLVMConfig.cmake.in @@ -73,6 +73,11 @@ find_package(ZLIB) endif() +set(LLVM_ENABLE_ICONV @LLVM_ENABLE_ICONV@) +if(LLVM_ENABLE_ICONV) + find_package(Iconv) +endif() + set(LLVM_ENABLE_ZSTD @LLVM_ENABLE_ZSTD@) if(LLVM_ENABLE_ZSTD) find_package(zstd) Index: llvm/docs/CMake.rst =================================================================== --- llvm/docs/CMake.rst +++ llvm/docs/CMake.rst @@ -497,6 +497,11 @@ FFI_LIBRARY_DIR to the directories where ffi.h and libffi.so can be found, respectively. Defaults to OFF. +**LLVM_ENABLE_ICONV**:BOOL + Enable building with iconv library to support conversion between different + character sets. + Defaults to ON. + **LLVM_ENABLE_IDE**:BOOL Tell the build system that an IDE is being used. This in turn disables the creation of certain convenience build system targets, such as the various Index: llvm/include/llvm/Config/config.h.cmake =================================================================== --- llvm/include/llvm/Config/config.h.cmake +++ llvm/include/llvm/Config/config.h.cmake @@ -287,6 +287,16 @@ /* Linker version detected at compile time. */ #cmakedefine HOST_LINK_VERSION "${HOST_LINK_VERSION}" +/* Target triple LLVM will generate code for by default */ +/* Doesn't use `cmakedefine` because it is allowed to be empty. */ +#define LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}" + +/* Define if zlib compression is available */ +#cmakedefine01 LLVM_ENABLE_ZLIB + +/* Define if iconv library is available */ +#cmakedefine01 LLVM_ENABLE_ICONV + /* Define if overriding target triple is enabled */ #cmakedefine LLVM_TARGET_TRIPLE_ENV "${LLVM_TARGET_TRIPLE_ENV}" Index: llvm/include/llvm/Support/CharSet.h =================================================================== --- /dev/null +++ llvm/include/llvm/Support/CharSet.h @@ -0,0 +1,178 @@ +//===-- CharSet.h - Utility class to convert between char sets ----*- C++ -*-=// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file provides a utility class to convert between different character +/// set encodings. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_CHARSET_H +#define LLVM_SUPPORT_CHARSET_H + +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Config/config.h" +#include "llvm/Support/ErrorOr.h" + +#include +#include +#include + +namespace llvm { + +template class SmallVectorImpl; + +namespace details { +class CharSetConverterImplBase { +public: + virtual ~CharSetConverterImplBase() = default; + + /// Converts a string. + /// \param[in] Source source string + /// \param[in,out] Result container for converted string + /// \param[in] ShouldAutoFlush Append shift-back sequence after conversion + /// for multi-byte encodings iff true. + /// \return error code in case something went wrong + /// + /// The following error codes can occur, among others: + /// - std::errc::argument_list_too_long: The result requires more than + /// std::numeric_limits::max() bytes. + /// - std::errc::illegal_byte_sequence: The input contains an invalid + /// multibyte sequence. + /// - std::errc::invalid_argument: The input contains an incomplete + /// multibyte sequence. + /// + /// In case of an error, the result string contains the successfully converted + /// part of the input string. + /// + /// If the Source parameter has a zero length, then no conversion is + /// performed. Instead, the internal conversation state of iconv is reset to + /// the initial state if iconv is used for the conversion. Otherwise it is a + /// no-op. + virtual std::error_code convert(StringRef Source, + SmallVectorImpl &Result, + bool ShouldAutoFlush) const = 0; + + /// Restore the conversion to the original state. + /// \return error code in case something went wrong + /// + /// If the original character set or the destination character set + /// are multi-byte character sets, set the shift state to the initial + /// state. Otherwise this is a no-op. + virtual std::error_code flush() const = 0; + + virtual std::error_code flush(SmallVectorImpl &Result) const = 0; +}; +} // namespace details + +// Names inspired by https://wg21.link/p1885. +namespace text_encoding { +enum class id { + /// UTF-8 character set encoding. + UTF8, + + /// ISO 8859-1 (Latin-1) character set encoding. + ISOLatin1, + + /// IBM EBCDIC 1047 character set encoding. + IBM1047 +}; +} // end namespace text_encoding + +/// Utility class to convert between different character set encodings. +/// The class always supports converting between EBCDIC 1047 and Latin-1/UTF-8. +/// If the iconv library is available, then arbitrary conversions are supported. +/// TODO Add Windows support. +class CharSetConverter { + std::unique_ptr Converter; + + CharSetConverter(std::unique_ptr Converter) + : Converter(std::move(Converter)) {} + +public: + /// Name for IBM EBCDIC 1047 character set encoding. + static const char *CP_IBM1047; + + /// Name for UTF-8 character set encoding. + static const char *CP_UTF8; + + /// Name for ISO 8859-1 (Latin-1) character set encoding. + static const char *CP_LATIN1; + + /// Creates a CharSetConverter instance. + /// \param[in] CSFrom name of the source character encoding + /// \param[in] CSTo name of the target character encoding + /// \return a CharSetConverter instance + static CharSetConverter create(text_encoding::id CSFrom, + text_encoding::id CSTo); + + /// Creates a CharSetConverter instance. + /// Returns std::errc::invalid_argument in case the requested conversion is + /// not supported. + /// \param[in] CPFrom name of the source character encoding + /// \param[in] CPTo name of the target character encoding + /// \return a CharSetConverter instance or an error code + static ErrorOr create(StringRef CPFrom, StringRef CPTo); + + static ErrorOr create(); + + CharSetConverter(const CharSetConverter &) = delete; + CharSetConverter &operator=(const CharSetConverter &) = delete; + + CharSetConverter(CharSetConverter &&Other) { + Converter = std::move(Other.Converter); + } + + CharSetConverter &operator=(CharSetConverter &&Other) { + if (this != &Other) + Converter = std::move(Other.Converter); + return *this; + } + + ~CharSetConverter() = default; + + /// Converts a string. + /// \param[in] Source source string + /// \param[in,out] Result container for converted string + /// \param[in] ShouldAutoFlush Append shift-back sequence after conversion + /// for multi-byte encodings. + /// \return error code in case something went wrong + std::error_code convert(StringRef Source, SmallVectorImpl &Result, + bool ShouldAutoFlush = true) const { + return Converter->convert(Source, Result, ShouldAutoFlush); + } + + char convert(char SingleChar) const { + SmallString<1> Result; + Converter->convert(StringRef(&SingleChar, 1), Result, false); + return Result[0]; + } + + /// Converts a string. + /// \param[in] Source source string + /// \param[in,out] Result container for converted string + /// \param[in] ShouldAutoFlush Append shift-back sequence after conversion + /// for multi-byte encodings iff true. + /// \return error code in case something went wrong + std::error_code convert(const std::string &Source, + SmallVectorImpl &Result, + bool ShouldAutoFlush = true) const { + return convert(StringRef(Source), Result, ShouldAutoFlush); + } + + std::error_code flush() const { return Converter->flush(); } + + std::error_code flush(SmallVectorImpl &Result) const { + return Converter->flush(Result); + } +}; + +} // namespace llvm + +#endif Index: llvm/lib/Support/CMakeLists.txt =================================================================== --- llvm/lib/Support/CMakeLists.txt +++ llvm/lib/Support/CMakeLists.txt @@ -87,6 +87,11 @@ set(system_libs ${system_libs} ${Z3_LIBRARIES}) endif() +# Link iconv library if it is an external library. +if(LLVM_ENABLE_ICONV AND NOT Iconv_IS_BUILT_IN) + set(system_libs ${system_libs} ${Iconv_LIBRARIES}) +endif() + # Override the C runtime allocator on Windows and embed it into LLVM tools & libraries if(LLVM_INTEGRATED_CRT_ALLOC) if (CMAKE_BUILD_TYPE AND NOT ${LLVM_USE_CRT_${uppercase_CMAKE_BUILD_TYPE}} MATCHES "^(MT|MTd)$") @@ -139,6 +144,7 @@ CachePruning.cpp Caching.cpp circular_raw_ostream.cpp + CharSet.cpp Chrono.cpp COM.cpp CodeGenCoverage.cpp @@ -329,6 +335,14 @@ endif() endif() +# Add include dir for iconv library if it is an external library. +if(LLVM_ENABLE_ICONV AND NOT Iconv_IS_BUILT_IN) + target_include_directories(LLVMSupport SYSTEM + PRIVATE + ${Iconv_INCLUDE_DIRS} + ) +endif() + if(LLVM_WITH_Z3) target_include_directories(LLVMSupport SYSTEM PRIVATE Index: llvm/lib/Support/CharSet.cpp =================================================================== --- /dev/null +++ llvm/lib/Support/CharSet.cpp @@ -0,0 +1,382 @@ +//===-- CharSet.cpp - Utility class to convert between char sets --*- C++ -*-=// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file provides utility classes to convert between different character +/// set encoding. +/// +//===----------------------------------------------------------------------===// + +#include "llvm/Support/CharSet.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/raw_ostream.h" +#include +#include +#include + +#ifdef HAVE_ICONV +#include +#endif + +using namespace llvm; + +const char *CharSetConverter::CP_IBM1047 = "IBM-1047"; +const char *CharSetConverter::CP_UTF8 = "UTF-8"; +const char *CharSetConverter::CP_LATIN1 = "ISO8859-1"; + +// Normalize the charset name with the charset alias matching algorithm proposed +// in https://www.unicode.org/reports/tr22/tr22-8.html#Charset_Alias_Matching. +void normalizeCharSetName(StringRef CSName, SmallVectorImpl &Normalized) { + bool PrevDigit = false; + for (auto Ch : CSName) { + if (isAlnum(Ch)) { + Ch = toLower(Ch); + if (Ch != '0' || PrevDigit) { + PrevDigit = isDigit(Ch); + Normalized.push_back(Ch); + } + } + } +} + +// Maps the charset name to enum constant if possible. +std::optional getKnownCharSet(StringRef CSName) { + SmallString<16> Normalized; + normalizeCharSetName(CSName, Normalized); +#define CSNAME(CS, STR) \ + if (Normalized.equals(STR)) \ + return CS + CSNAME(text_encoding::id::UTF8, "utf8"); + CSNAME(text_encoding::id::ISOLatin1, "iso88591"); + CSNAME(text_encoding::id::IBM1047, "ibm1047"); +#undef CSNAME + return std::nullopt; +} + +namespace { +// Character conversion between Enhanced ASCII and EBCDIC (IBM-1047). +const unsigned char ISO88591ToIBM1047[256] = { + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, 0x16, 0x05, 0x15, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, + 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, 0x40, 0x5a, 0x7f, 0x7b, + 0x5b, 0x6c, 0x50, 0x7d, 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0x7a, 0x5e, + 0x4c, 0x7e, 0x6e, 0x6f, 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xad, 0xe0, 0xbd, 0x5f, 0x6d, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, + 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, + 0xa7, 0xa8, 0xa9, 0xc0, 0x4f, 0xd0, 0xa1, 0x07, 0x20, 0x21, 0x22, 0x23, + 0x24, 0x25, 0x06, 0x17, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x1b, + 0x30, 0x31, 0x1a, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3a, 0x3b, + 0x04, 0x14, 0x3e, 0xff, 0x41, 0xaa, 0x4a, 0xb1, 0x9f, 0xb2, 0x6a, 0xb5, + 0xbb, 0xb4, 0x9a, 0x8a, 0xb0, 0xca, 0xaf, 0xbc, 0x90, 0x8f, 0xea, 0xfa, + 0xbe, 0xa0, 0xb6, 0xb3, 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, 0x74, 0x71, 0x72, 0x73, + 0x78, 0x75, 0x76, 0x77, 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, + 0x80, 0xfd, 0xfe, 0xfb, 0xfc, 0xba, 0xae, 0x59, 0x44, 0x45, 0x42, 0x46, + 0x43, 0x47, 0x9c, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, 0x70, 0xdd, 0xde, 0xdb, + 0xdc, 0x8d, 0x8e, 0xdf}; + +const unsigned char IBM1047ToISO88591[256] = { + 0x00, 0x01, 0x02, 0x03, 0x9c, 0x09, 0x86, 0x7f, 0x97, 0x8d, 0x8e, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x9d, 0x0a, 0x08, 0x87, + 0x18, 0x19, 0x92, 0x8f, 0x1c, 0x1d, 0x1e, 0x1f, 0x80, 0x81, 0x82, 0x83, + 0x84, 0x85, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, + 0x14, 0x15, 0x9e, 0x1a, 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, + 0xe7, 0xf1, 0xa2, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, 0x26, 0xe9, 0xea, 0xeb, + 0xe8, 0xed, 0xee, 0xef, 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x5e, + 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, 0xc7, 0xd1, 0xa6, 0x2c, + 0x25, 0x5f, 0x3e, 0x3f, 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, + 0xcc, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, 0xd8, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, + 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xaa, 0xba, + 0xe6, 0xb8, 0xc6, 0xa4, 0xb5, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0x5b, 0xde, 0xae, 0xac, 0xa3, 0xa5, 0xb7, + 0xa9, 0xa7, 0xb6, 0xbc, 0xbd, 0xbe, 0xdd, 0xa8, 0xaf, 0x5d, 0xb4, 0xd7, + 0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xad, 0xf4, + 0xf6, 0xf2, 0xf3, 0xf5, 0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, + 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xf9, 0xfa, 0xff, 0x5c, 0xf7, 0x53, 0x54, + 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xb3, 0xdb, + 0xdc, 0xd9, 0xda, 0x9f}; + +enum { NoUTF = 0x0, SrcIsUTF = 0x1, DstIsUTF = 0x2 }; + +class CharSetConverterIdentity : public details::CharSetConverterImplBase { +public: + std::error_code convert(StringRef Source, SmallVectorImpl &Result, + bool ShouldAutoFlush) const override; + std::error_code flush() const override; + std::error_code flush(SmallVectorImpl &Result) const override; +}; + +std::error_code CharSetConverterIdentity::convert(StringRef Source, + SmallVectorImpl &Result, + bool ShouldAutoFlush) const { + Result.assign(Source.begin(), Source.end()); + return std::error_code(); +} + +std::error_code CharSetConverterIdentity::flush() const { + return std::error_code(); +} + +std::error_code +CharSetConverterIdentity::flush(SmallVectorImpl &Result) const { + return std::error_code(); +} + +class CharSetConverterTable : public details::CharSetConverterImplBase { + const unsigned char *Table; + unsigned Flags; + +public: + CharSetConverterTable(const unsigned char *Table, unsigned Flags) + : Table(Table), Flags(Flags) {} + + std::error_code convert(StringRef Source, SmallVectorImpl &Result, + bool ShouldAutoFlush) const override; + std::error_code flush() const override; + std::error_code flush(SmallVectorImpl &Result) const override; +}; + +std::error_code CharSetConverterTable::convert(StringRef Source, + SmallVectorImpl &Result, + bool ShouldAutoFlush) const { + const unsigned char *Ptr = + reinterpret_cast(Source.data()); + size_t Length = Source.size(); + // To maintain common behaviour as convertWithIconv since that overwites + // the output buffer. + Result.clear(); + while (Length--) { + unsigned char Ch = *Ptr++; + // Handle UTF-8 2-byte-sequences in input. + if (Flags == SrcIsUTF) { + if (Ch >= 128) { + // Only two-byte sequences can be decoded. + if (Ch != 0xc2 && Ch != 0xc3) + return std::make_error_code(std::errc::illegal_byte_sequence); + // Is buffer truncated? + if (!Length) + return std::make_error_code(std::errc::invalid_argument); + unsigned char Ch2 = *Ptr++; + // Is second byte well-formed? + if ((Ch2 & 0xc0) != 0x80) + return std::make_error_code(std::errc::illegal_byte_sequence); + Ch = Ch2 | (Ch << 6); + Length--; + } + } + // Translate the character. + Ch = Table[Ch]; + // Handle UTF-8 2-byte-sequences in output. + if (Flags == DstIsUTF) { + if (Ch >= 128) { + // First byte prefixed with either 0xc2 or 0xc3. + Result.push_back(static_cast(0xc0 | (Ch >> 6))); + // Second byte is either the same as the ASCII byte or ASCII byte -64. + Ch = Ch & 0xbf; + } + } + Result.push_back(static_cast(Ch)); + } + return std::error_code(); +} + +std::error_code CharSetConverterTable::flush() const { + return std::error_code(); +} + +std::error_code +CharSetConverterTable::flush(SmallVectorImpl &Result) const { + return std::error_code(); +} + +#ifdef HAVE_ICONV +class CharSetConverterIconv : public details::CharSetConverterImplBase { + iconv_t ConvDesc; + +public: + CharSetConverterIconv(iconv_t ConvDesc) : ConvDesc(ConvDesc) {} + + std::error_code convert(StringRef Source, SmallVectorImpl &Result, + bool ShouldAutoFlush) const override; + std::error_code flush() const override; + std::error_code flush(SmallVectorImpl &Result) const override; +}; + +std::error_code CharSetConverterIconv::convert(StringRef Source, + SmallVectorImpl &Result, + bool ShouldAutoFlush) const { + // Setup the input. Use nullptr to reset iconv state if input length is zero. + size_t InputLength = Source.size(); + char *Input = InputLength ? const_cast(Source.data()) : nullptr; + // Setup the output. We directly write into the SmallVector. + size_t Capacity = Result.capacity(); + Result.resize_for_overwrite(Capacity); + char *Output = InputLength ? static_cast(Result.data()) : nullptr; + size_t OutputLength = Capacity; + + size_t Ret; + + // Handle errors returned from iconv(). + auto HandleError = [&Capacity, &Output, &OutputLength, &Result](size_t Ret) { + if (Ret == static_cast(-1)) { + // An error occured. Check if we can gracefully handle it. + if (errno == E2BIG && Capacity < std::numeric_limits::max()) { + // No space left in output buffer. Double the size of the underlying + // memory in the SmallVectorImpl, adjust pointer and length and continue + // the conversion. + const size_t Used = Capacity - OutputLength; + Capacity = (Capacity < std::numeric_limits::max() / 2) + ? 2 * Capacity + : std::numeric_limits::max(); + Result.resize_for_overwrite(Capacity); + Output = static_cast(Result.data()) + Used; + OutputLength = Capacity - Used; + return std::error_code(); + } else { + // Some other error occured. + return std::error_code(errno, std::generic_category()); + } + } else { + // A positive return value indicates that some characters were converted + // in a nonreversible way, that is, replaced with a SUB symbol. Returning + // an error in this case makes sure that both conversion routines behave + // in the same way. + return std::make_error_code(std::errc::illegal_byte_sequence); + } + }; + + // Convert the string. + while ((Ret = iconv(ConvDesc, &Input, &InputLength, &Output, &OutputLength))) + if (auto EC = HandleError(Ret)) + return EC; + if (ShouldAutoFlush) { + while ((Ret = iconv(ConvDesc, nullptr, nullptr, &Output, &OutputLength))) + if (auto EC = HandleError(Ret)) + return EC; + } + + // Re-adjust size to actual size. + Result.resize(Capacity - OutputLength); + return std::error_code(); +} + +std::error_code CharSetConverterIconv::flush() const { + size_t Ret = iconv(ConvDesc, nullptr, nullptr, nullptr, nullptr); + if (Ret == static_cast(-1)) { + return std::error_code(errno, std::generic_category()); + } + return std::error_code(); +} + +std::error_code +CharSetConverterIconv::flush(SmallVectorImpl &Result) const { + char *Output = Result.data(); + size_t OutputLength = Result.capacity(); + size_t Capacity = Result.capacity(); + Result.resize_for_overwrite(Capacity); + + // Handle errors returned from iconv(). + auto HandleError = [&Capacity, &Output, &OutputLength, &Result](size_t Ret) { + if (Ret == static_cast(-1)) { + // An error occured. Check if we can gracefully handle it. + if (errno == E2BIG && Capacity < std::numeric_limits::max()) { + // No space left in output buffer. Increase the size of the underlying + // memory in the SmallVectorImpl by 2 bytes, adjust pointer and length + // and continue the conversion. + const size_t Used = Capacity - OutputLength; + Capacity = (Capacity < std::numeric_limits::max() - 2) + ? 2 + Capacity + : std::numeric_limits::max(); + Result.resize_for_overwrite(Capacity); + Output = static_cast(Result.data()) + Used; + OutputLength = Capacity - Used; + return std::error_code(); + } else { + // Some other error occured. + return std::error_code(errno, std::generic_category()); + } + } else { + // A positive return value indicates that some characters were converted + // in a nonreversible way, that is, replaced with a SUB symbol. Returning + // an error in this case makes sure that both conversion routines behave + // in the same way. + return std::make_error_code(std::errc::illegal_byte_sequence); + } + }; + + size_t Ret; + while ((Ret = iconv(ConvDesc, nullptr, nullptr, &Output, &OutputLength))) + if (auto EC = HandleError(Ret)) + return EC; + + // Re-adjust size to actual size. + Result.resize(Capacity - OutputLength); + return std::error_code(); +} + +#endif // HAVE_ICONV +} // namespace + +CharSetConverter CharSetConverter::create(text_encoding::id CPFrom, + text_encoding::id CPTo) { + + // Special case: identity transformation. + if (CPFrom == CPTo) { + std::unique_ptr Converter = + std::make_unique(); + return CharSetConverter(std::move(Converter)); + } + + unsigned Flags = NoUTF; + if (CPFrom == text_encoding::id::UTF8) + Flags |= SrcIsUTF; + if (CPTo == text_encoding::id::UTF8) + Flags |= DstIsUTF; + + const unsigned char *Table = nullptr; + if (CPFrom == text_encoding::id::IBM1047) + Table = IBM1047ToISO88591; + else if (CPTo == text_encoding::id::IBM1047) + Table = ISO88591ToIBM1047; + + std::unique_ptr Converter = + std::make_unique(Table, Flags); + return CharSetConverter(std::move(Converter)); +} + +ErrorOr CharSetConverter::create(StringRef CSFrom, + StringRef CSTo) { + std::optional From = getKnownCharSet(CSFrom); + std::optional To = getKnownCharSet(CSTo); + if (From && To) + return create(*From, *To); +#if HAVE_ICONV + iconv_t ConvDesc = iconv_open(CSTo.str().c_str(), CSFrom.str().c_str()); + if (ConvDesc == (iconv_t)-1) + return std::error_code(errno, std::generic_category()); + std::unique_ptr Converter = + std::make_unique(ConvDesc); + return CharSetConverter(std::move(Converter)); +#endif + return std::make_error_code(std::errc::invalid_argument); +} + +ErrorOr CharSetConverter::create() { + std::unique_ptr Converter = + std::make_unique(); + return CharSetConverter(std::move(Converter)); +} Index: llvm/unittests/Support/CMakeLists.txt =================================================================== --- llvm/unittests/Support/CMakeLists.txt +++ llvm/unittests/Support/CMakeLists.txt @@ -16,6 +16,7 @@ BlockFrequencyTest.cpp BranchProbabilityTest.cpp CachePruningTest.cpp + CharSetTest.cpp CrashRecoveryTest.cpp Casting.cpp CheckedArithmeticTest.cpp Index: llvm/unittests/Support/CharSetTest.cpp =================================================================== --- /dev/null +++ llvm/unittests/Support/CharSetTest.cpp @@ -0,0 +1,323 @@ +//===- unittests/Support/CharSetTest.cpp - Charset conversion tests -------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "llvm/Support/CharSet.h" +#include "llvm/ADT/SmallString.h" +#include "gtest/gtest.h" +using namespace llvm; + +namespace { + +// String "Hello World!" +static const char HelloA[] = + "\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21\x0a"; +static const char HelloE[] = + "\xC8\x85\x93\x93\x96\x40\xE6\x96\x99\x93\x84\x5A\x15"; + +// String "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +static const char ABCStrA[] = + "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52" + "\x53\x54\x55\x56\x57\x58\x59\x5A\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A" + "\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A"; +static const char ABCStrE[] = + "\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9" + "\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91" + "\x92\x93\x94\x95\x96\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9"; + +// String "¡¢£AÄÅÆEÈÉÊaàáâãäeèéêë" +static const char AccentUTF[] = + "\xc2\xa1\xc2\xa2\xc2\xa3\x41\xc3\x84\xc3\x85\xc3\x86\x45\xc3\x88\xc3\x89" + "\xc3\x8a\x61\xc3\xa0\xc3\xa1\xc3\xa2\xc3\xa3\xc3\xa4\x65\xc3\xa8\xc3\xa9" + "\xc3\xaa\xc3\xab"; +static const char AccentE[] = "\xaa\x4a\xb1\xc1\x63\x67\x9e\xc5\x74\x71\x72" + "\x81\x44\x45\x42\x46\x43\x85\x54\x51\x52\x53"; + +// String with Cyrillic character ya. +static const char CyrillicUTF[] = "\xd0\xaf"; + +// String "Earth地球". +// ISO-2022-JP: Sequence ESC $ B (\x1B\x24\x42) switches to JIS X 0208-1983, and +// sequence ESC ( B (\x1B\x28\x42) switches back to ASCII. +// IBM-939: Byte 0x0E shifts from single byte to double byte, and 0x0F shifts +// back. +static const char EarthUTF[] = "\x45\x61\x72\x74\x68\xe5\x9c\xb0\xe7\x90\x83"; +// Identical to above, except the final character (球) has its last byte taken +// away from it. +static const char EarthUTFBroken[] = "\x45\x61\x72\x74\x68\xe5\x9c\xb0\xe7\x90"; +static const char EarthISO2022[] = + "\x45\x61\x72\x74\x68\x1B\x24\x42\x43\x4F\x35\x65\x1B\x28\x42"; +static const char EarthISO2022ShiftBack[] = + "\x45\x61\x72\x74\x68\x1B\x24\x42\x43\x4F\x35\x65"; +static const char EarthIBM939[] = + "\xc5\x81\x99\xa3\x88\x0e\x45\xc2\x48\xdb\x0f"; +static const char ShiftBackOnly[] = "\x1B\x28\x42"; + +// String "地球". +static const char EarthKanjiOnlyUTF[] = "\xe5\x9c\xb0\xe7\x90\x83"; +static const char EarthKanjiOnlyISO2022[] = + "\x1B\x24\x42\x43\x4F\x35\x65\x1b\x28\x42"; +static const char EarthKanjiOnlyIBM939[] = "\x0e\x45\xc2\x48\xdb\x0f"; + +TEST(CharSet, FromASCII) { + // Hello string. + StringRef Src(HelloA); + SmallString<64> Dst; + + CharSetConverter Conv = CharSetConverter::create(text_encoding::id::ISOLatin1, + text_encoding::id::IBM1047); + std::error_code EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(HelloE, static_cast(Dst).c_str()); + + // ABC string. + Src = ABCStrA; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(ABCStrE, static_cast(Dst).c_str()); +} + +TEST(CharSet, ToASCII) { + // Hello string. + StringRef Src(HelloE); + SmallString<64> Dst; + + CharSetConverter Conv = CharSetConverter::create( + text_encoding::id::IBM1047, text_encoding::id::ISOLatin1); + std::error_code EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(HelloA, static_cast(Dst).c_str()); + + // ABC string. + Src = ABCStrE; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(ABCStrA, static_cast(Dst).c_str()); +} + +TEST(CharSet, FromUTF8) { + // Hello string. + StringRef Src(HelloA); + SmallString<64> Dst; + + CharSetConverter Conv = CharSetConverter::create(text_encoding::id::UTF8, + text_encoding::id::IBM1047); + std::error_code EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(HelloE, static_cast(Dst).c_str()); + + // ABC string. + Src = ABCStrA; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(ABCStrE, static_cast(Dst).c_str()); + + // Accent string. + Src = AccentUTF; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(AccentE, static_cast(Dst).c_str()); + + // Cyrillic string. Results in error because not representable in 1047. + Src = CyrillicUTF; + EC = Conv.convert(Src, Dst, true); + EXPECT_EQ(EC, std::errc::illegal_byte_sequence); +} + +TEST(CharSet, ToUTF8) { + // Hello string. + StringRef Src(HelloE); + SmallString<64> Dst; + + CharSetConverter Conv = CharSetConverter::create(text_encoding::id::IBM1047, + text_encoding::id::UTF8); + std::error_code EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(HelloA, static_cast(Dst).c_str()); + + // ABC string. + Src = ABCStrE; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(ABCStrA, static_cast(Dst).c_str()); + + // Accent string. + Src = AccentE; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(AccentUTF, static_cast(Dst).c_str()); +} + +TEST(CharSet, Identity) { + // Hello string. + StringRef Src(HelloA); + SmallString<64> Dst; + + CharSetConverter Conv = CharSetConverter::create( + text_encoding::id::ISOLatin1, text_encoding::id::ISOLatin1); + std::error_code EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(HelloA, static_cast(Dst).c_str()); + + // ABC string. + Src = ABCStrA; + EC = Conv.convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(ABCStrA, static_cast(Dst).c_str()); +} + +TEST(CharSet, RoundTrip) { + ErrorOr ConvToUTF16 = + CharSetConverter::create("IBM-1047", "UTF-16"); + // Stop test if conversion is not supported (no underlying iconv support). + if (!ConvToUTF16) { + ASSERT_EQ(ConvToUTF16.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + ErrorOr ConvToUTF32 = + CharSetConverter::create("UTF-16", "UTF-32"); + // Stop test if conversion is not supported (no underlying iconv support). + if (!ConvToUTF32) { + ASSERT_EQ(ConvToUTF32.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + ErrorOr ConvToEBCDIC = + CharSetConverter::create("UTF-32", "IBM-1047"); + // Stop test if conversion is not supported (no underlying iconv support). + if (!ConvToEBCDIC) { + ASSERT_EQ(ConvToEBCDIC.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + + // Setup source string. + char SrcStr[256]; + for (size_t I = 0; I < 256; ++I) + SrcStr[I] = (I + 1) % 256; + + SmallString<99> Dst1Str, Dst2Str, Dst3Str; + + std::error_code EC = ConvToUTF16->convert(StringRef(SrcStr), Dst1Str, true); + EXPECT_TRUE(!EC); + EC = ConvToUTF32->convert(Dst1Str, Dst2Str, true); + EXPECT_TRUE(!EC); + EC = ConvToEBCDIC->convert(Dst2Str, Dst3Str, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(SrcStr, static_cast(Dst3Str).c_str()); +} + +TEST(CharSet, ShiftState2022) { + // Earth string. + StringRef Src(EarthUTF); + SmallString<64> Dst; + + ErrorOr ConvTo2022 = + CharSetConverter::create("UTF-8", "ISO-2022-JP"); + // Stop test if conversion is not supported (no underlying iconv support). + if (!ConvTo2022) { + ASSERT_EQ(ConvTo2022.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + + // Check that the string is properly converted. + std::error_code EC = ConvTo2022->convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(EarthISO2022, static_cast(Dst).c_str()); +} + +TEST(CharSet, ShiftState2022Flush) { + StringRef Src0(EarthUTFBroken); + StringRef Src1(EarthKanjiOnlyUTF); + SmallString<64> Dst0; + SmallString<64> Dst1; + ErrorOr ConvTo2022Flush = + CharSetConverter::create("UTF-8", "ISO-2022-JP"); + if (!ConvTo2022Flush) { + ASSERT_EQ(ConvTo2022Flush.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + + // This should emit an error; there is a malformed multibyte character in the + // input string. + std::error_code EC0 = ConvTo2022Flush->convert(Src0, Dst0, true); + EXPECT_TRUE(EC0); + std::error_code EC1 = ConvTo2022Flush->flush(); + EXPECT_TRUE(!EC1); + std::error_code EC2 = ConvTo2022Flush->convert(Src1, Dst1, true); + EXPECT_TRUE(!EC2); + EXPECT_STREQ(EarthKanjiOnlyISO2022, static_cast(Dst1).c_str()); +} + +TEST(CharSet, ShiftStateIBM939) { + // Earth string. + StringRef Src(EarthUTF); + SmallString<64> Dst; + + ErrorOr ConvToIBM939 = + CharSetConverter::create("UTF-8", "IBM-939"); + // Stop test if conversion is not supported (no underlying iconv support). + if (!ConvToIBM939) { + ASSERT_EQ(ConvToIBM939.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + + // Check that the string is properly converted. + std::error_code EC = ConvToIBM939->convert(Src, Dst, true); + EXPECT_TRUE(!EC); + EXPECT_STREQ(EarthIBM939, static_cast(Dst).c_str()); +} + +TEST(CharSet, ShiftStateIBM939Flush) { + StringRef Src0(EarthUTFBroken); + StringRef Src1(EarthKanjiOnlyUTF); + SmallString<64> Dst0; + SmallString<64> Dst1; + ErrorOr ConvTo939Flush = + CharSetConverter::create("UTF-8", "IBM-939"); + if (!ConvTo939Flush) { + ASSERT_EQ(ConvTo939Flush.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + + // This should emit an error; there is a malformed multibyte character in the + // input string. + std::error_code EC0 = ConvTo939Flush->convert(Src0, Dst0, true); + EXPECT_TRUE(EC0); + std::error_code EC1 = ConvTo939Flush->flush(); + EXPECT_TRUE(!EC1); + std::error_code EC2 = ConvTo939Flush->convert(Src1, Dst1, true); + EXPECT_TRUE(!EC2); + EXPECT_STREQ(EarthKanjiOnlyIBM939, static_cast(Dst1).c_str()); +} + +TEST(CharSet, ShiftState2022Flush1) { + StringRef Src0(EarthUTF); + SmallString<64> Dst0; + SmallString<64> Dst1; + ErrorOr ConvTo2022Flush = + CharSetConverter::create("UTF-8", "ISO-2022-JP"); + if (!ConvTo2022Flush) { + ASSERT_EQ(ConvTo2022Flush.getError(), + std::make_error_code(std::errc::invalid_argument)); + return; + } + + std::error_code EC0 = ConvTo2022Flush->convert(Src0, Dst0, false); + EXPECT_TRUE(!EC0); + EXPECT_STREQ(EarthISO2022ShiftBack, static_cast(Dst0).c_str()); + std::error_code EC1 = ConvTo2022Flush->flush(Dst1); + EXPECT_TRUE(!EC1); + EXPECT_STREQ(ShiftBackOnly, static_cast(Dst1).c_str()); +} + +} // namespace