Home | History | Annotate | Download | only in text
      1 /*
      2  * Copyright (C) 2004, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
      3  * Copyright (C) 2006 Alexey Proskuryakov <ap (at) nypop.com>
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  *
     14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
     15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
     18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     25  */
     26 
     27 #include "config.h"
     28 #include "wtf/text/TextCodecICU.h"
     29 
     30 #include <unicode/ucnv.h>
     31 #include <unicode/ucnv_cb.h>
     32 #include "wtf/Assertions.h"
     33 #include "wtf/StringExtras.h"
     34 #include "wtf/Threading.h"
     35 #include "wtf/WTFThreadData.h"
     36 #include "wtf/text/CString.h"
     37 #include "wtf/text/StringBuilder.h"
     38 #include "wtf/unicode/CharacterNames.h"
     39 
     40 using std::min;
     41 
     42 namespace WTF {
     43 
     44 const size_t ConversionBufferSize = 16384;
     45 
     46 ICUConverterWrapper::~ICUConverterWrapper()
     47 {
     48     if (converter)
     49         ucnv_close(converter);
     50 }
     51 
     52 static UConverter*& cachedConverterICU()
     53 {
     54     return wtfThreadData().cachedConverterICU().converter;
     55 }
     56 
     57 PassOwnPtr<TextCodec> TextCodecICU::create(const TextEncoding& encoding, const void*)
     58 {
     59     return adoptPtr(new TextCodecICU(encoding));
     60 }
     61 
     62 void TextCodecICU::registerEncodingNames(EncodingNameRegistrar registrar)
     63 {
     64     // We register Hebrew with logical ordering using a separate name.
     65     // Otherwise, this would share the same canonical name as the
     66     // visual ordering case, and then TextEncoding could not tell them
     67     // apart; ICU treats these names as synonyms.
     68     registrar("ISO-8859-8-I", "ISO-8859-8-I");
     69 
     70     int32_t numEncodings = ucnv_countAvailable();
     71     for (int32_t i = 0; i < numEncodings; ++i) {
     72         const char* name = ucnv_getAvailableName(i);
     73         UErrorCode error = U_ZERO_ERROR;
     74         // Try MIME before trying IANA to pick up commonly used names like
     75         // 'EUC-JP' instead of horrendously long names like
     76         // 'Extended_UNIX_Code_Packed_Format_for_Japanese'.
     77         const char* standardName = ucnv_getStandardName(name, "MIME", &error);
     78         if (!U_SUCCESS(error) || !standardName) {
     79             error = U_ZERO_ERROR;
     80             // Try IANA to pick up 'windows-12xx' and other names
     81             // which are not preferred MIME names but are widely used.
     82             standardName = ucnv_getStandardName(name, "IANA", &error);
     83             if (!U_SUCCESS(error) || !standardName)
     84                 continue;
     85         }
     86 
     87         // 1. Treat GB2312 encoding as GBK (its more modern superset), to match other browsers.
     88         // 2. On the Web, GB2312 is encoded as EUC-CN or HZ, while ICU provides a native encoding
     89         //    for encoding GB_2312-80 and several others. So, we need to override this behavior, too.
     90         if (strcmp(standardName, "GB2312") == 0 || strcmp(standardName, "GB_2312-80") == 0)
     91             standardName = "GBK";
     92         // Similarly, EUC-KR encodings all map to an extended version.
     93         else if (strcmp(standardName, "KSC_5601") == 0 || strcmp(standardName, "EUC-KR") == 0 || strcmp(standardName, "cp1363") == 0)
     94             standardName = "windows-949";
     95         // And so on.
     96         else if (strcasecmp(standardName, "iso-8859-9") == 0) // This name is returned in different case by ICU 3.2 and 3.6.
     97             standardName = "windows-1254";
     98         else if (strcmp(standardName, "TIS-620") == 0)
     99             standardName = "windows-874";
    100 
    101         registrar(standardName, standardName);
    102 
    103         uint16_t numAliases = ucnv_countAliases(name, &error);
    104         ASSERT(U_SUCCESS(error));
    105         if (U_SUCCESS(error))
    106             for (uint16_t j = 0; j < numAliases; ++j) {
    107                 error = U_ZERO_ERROR;
    108                 const char* alias = ucnv_getAlias(name, j, &error);
    109                 ASSERT(U_SUCCESS(error));
    110                 if (U_SUCCESS(error) && alias != standardName)
    111                     registrar(alias, standardName);
    112             }
    113     }
    114 
    115     // Additional aliases.
    116     // These are present in modern versions of ICU, but not in ICU 3.2 (shipped with Mac OS X 10.4).
    117     registrar("macroman", "macintosh");
    118     registrar("maccyrillic", "x-mac-cyrillic");
    119 
    120     // Additional aliases that historically were present in the encoding
    121     // table in WebKit on Macintosh that don't seem to be present in ICU.
    122     // Perhaps we can prove these are not used on the web and remove them.
    123     // Or perhaps we can get them added to ICU.
    124     registrar("x-mac-roman", "macintosh");
    125     registrar("x-mac-ukrainian", "x-mac-cyrillic");
    126     registrar("cn-big5", "Big5");
    127     registrar("x-x-big5", "Big5");
    128     registrar("cn-gb", "GBK");
    129     registrar("csgb231280", "GBK");
    130     registrar("x-euc-cn", "GBK");
    131     registrar("x-gbk", "GBK");
    132     registrar("csISO88598I", "ISO-8859-8-I");
    133     registrar("koi", "KOI8-R");
    134     registrar("logical", "ISO-8859-8-I");
    135     registrar("visual", "ISO-8859-8");
    136     registrar("winarabic", "windows-1256");
    137     registrar("winbaltic", "windows-1257");
    138     registrar("wincyrillic", "windows-1251");
    139     registrar("iso-8859-11", "windows-874");
    140     registrar("iso8859-11", "windows-874");
    141     registrar("dos-874", "windows-874");
    142     registrar("wingreek", "windows-1253");
    143     registrar("winhebrew", "windows-1255");
    144     registrar("winlatin2", "windows-1250");
    145     registrar("winturkish", "windows-1254");
    146     registrar("winvietnamese", "windows-1258");
    147     registrar("x-cp1250", "windows-1250");
    148     registrar("x-cp1251", "windows-1251");
    149     registrar("x-euc", "EUC-JP");
    150     registrar("x-windows-949", "windows-949");
    151     registrar("KSC5601", "KSC_5601");
    152     registrar("x-uhc", "windows-949");
    153     registrar("shift-jis", "Shift_JIS");
    154 
    155     // These aliases are present in modern versions of ICU, but use different codecs, and have no standard names.
    156     // They are not present in ICU 3.2.
    157     registrar("dos-720", "cp864");
    158     registrar("jis7", "ISO-2022-JP");
    159 
    160     // Alternative spelling of ISO encoding names.
    161     registrar("ISO8859-1", "ISO-8859-1");
    162     registrar("ISO8859-2", "ISO-8859-2");
    163     registrar("ISO8859-3", "ISO-8859-3");
    164     registrar("ISO8859-4", "ISO-8859-4");
    165     registrar("ISO8859-5", "ISO-8859-5");
    166     registrar("ISO8859-6", "ISO-8859-6");
    167     registrar("ISO8859-7", "ISO-8859-7");
    168     registrar("ISO8859-8", "ISO-8859-8");
    169     registrar("ISO8859-8-I", "ISO-8859-8-I");
    170     registrar("ISO8859-9", "ISO-8859-9");
    171     registrar("ISO8859-10", "ISO-8859-10");
    172     registrar("ISO8859-13", "ISO-8859-13");
    173     registrar("ISO8859-14", "ISO-8859-14");
    174     registrar("ISO8859-15", "ISO-8859-15");
    175     // Not registering ISO8859-16, because Firefox (as of version 3.6.6) doesn't know this particular alias,
    176     // and because older versions of ICU don't support ISO-8859-16 encoding at all.
    177 }
    178 
    179 void TextCodecICU::registerCodecs(TextCodecRegistrar registrar)
    180 {
    181     // See comment above in registerEncodingNames.
    182     registrar("ISO-8859-8-I", create, 0);
    183 
    184     int32_t numEncodings = ucnv_countAvailable();
    185     for (int32_t i = 0; i < numEncodings; ++i) {
    186         const char* name = ucnv_getAvailableName(i);
    187         UErrorCode error = U_ZERO_ERROR;
    188         const char* standardName = ucnv_getStandardName(name, "MIME", &error);
    189         if (!U_SUCCESS(error) || !standardName) {
    190             error = U_ZERO_ERROR;
    191             standardName = ucnv_getStandardName(name, "IANA", &error);
    192             if (!U_SUCCESS(error) || !standardName)
    193                 continue;
    194         }
    195         registrar(standardName, create, 0);
    196     }
    197 }
    198 
    199 TextCodecICU::TextCodecICU(const TextEncoding& encoding)
    200     : m_encoding(encoding)
    201     , m_converterICU(0)
    202     , m_needsGBKFallbacks(false)
    203 {
    204 }
    205 
    206 TextCodecICU::~TextCodecICU()
    207 {
    208     releaseICUConverter();
    209 }
    210 
    211 void TextCodecICU::releaseICUConverter() const
    212 {
    213     if (m_converterICU) {
    214         UConverter*& cachedConverter = cachedConverterICU();
    215         if (cachedConverter)
    216             ucnv_close(cachedConverter);
    217         cachedConverter = m_converterICU;
    218         m_converterICU = 0;
    219     }
    220 }
    221 
    222 void TextCodecICU::createICUConverter() const
    223 {
    224     ASSERT(!m_converterICU);
    225 
    226     const char* name = m_encoding.name();
    227     m_needsGBKFallbacks = name[0] == 'G' && name[1] == 'B' && name[2] == 'K' && !name[3];
    228 
    229     UErrorCode err;
    230 
    231     UConverter*& cachedConverter = cachedConverterICU();
    232     if (cachedConverter) {
    233         err = U_ZERO_ERROR;
    234         const char* cachedName = ucnv_getName(cachedConverter, &err);
    235         if (U_SUCCESS(err) && m_encoding == cachedName) {
    236             m_converterICU = cachedConverter;
    237             cachedConverter = 0;
    238             return;
    239         }
    240     }
    241 
    242     err = U_ZERO_ERROR;
    243     m_converterICU = ucnv_open(m_encoding.name(), &err);
    244 #if !LOG_DISABLED
    245     if (err == U_AMBIGUOUS_ALIAS_WARNING)
    246         LOG_ERROR("ICU ambiguous alias warning for encoding: %s", m_encoding.name());
    247 #endif
    248     if (m_converterICU)
    249         ucnv_setFallback(m_converterICU, TRUE);
    250 }
    251 
    252 int TextCodecICU::decodeToBuffer(UChar* target, UChar* targetLimit, const char*& source, const char* sourceLimit, int32_t* offsets, bool flush, UErrorCode& err)
    253 {
    254     UChar* targetStart = target;
    255     err = U_ZERO_ERROR;
    256     ucnv_toUnicode(m_converterICU, &target, targetLimit, &source, sourceLimit, offsets, flush, &err);
    257     return target - targetStart;
    258 }
    259 
    260 class ErrorCallbackSetter {
    261 public:
    262     ErrorCallbackSetter(UConverter* converter, bool stopOnError)
    263         : m_converter(converter)
    264         , m_shouldStopOnEncodingErrors(stopOnError)
    265     {
    266         if (m_shouldStopOnEncodingErrors) {
    267             UErrorCode err = U_ZERO_ERROR;
    268             ucnv_setToUCallBack(m_converter, UCNV_TO_U_CALLBACK_SUBSTITUTE,
    269                            UCNV_SUB_STOP_ON_ILLEGAL, &m_savedAction,
    270                            &m_savedContext, &err);
    271             ASSERT(err == U_ZERO_ERROR);
    272         }
    273     }
    274     ~ErrorCallbackSetter()
    275     {
    276         if (m_shouldStopOnEncodingErrors) {
    277             UErrorCode err = U_ZERO_ERROR;
    278             const void* oldContext;
    279             UConverterToUCallback oldAction;
    280             ucnv_setToUCallBack(m_converter, m_savedAction,
    281                    m_savedContext, &oldAction,
    282                    &oldContext, &err);
    283             ASSERT(oldAction == UCNV_TO_U_CALLBACK_SUBSTITUTE);
    284             ASSERT(!strcmp(static_cast<const char*>(oldContext), UCNV_SUB_STOP_ON_ILLEGAL));
    285             ASSERT(err == U_ZERO_ERROR);
    286         }
    287     }
    288 
    289 private:
    290     UConverter* m_converter;
    291     bool m_shouldStopOnEncodingErrors;
    292     const void* m_savedContext;
    293     UConverterToUCallback m_savedAction;
    294 };
    295 
    296 String TextCodecICU::decode(const char* bytes, size_t length, bool flush, bool stopOnError, bool& sawError)
    297 {
    298     // Get a converter for the passed-in encoding.
    299     if (!m_converterICU) {
    300         createICUConverter();
    301         ASSERT(m_converterICU);
    302         if (!m_converterICU) {
    303             LOG_ERROR("error creating ICU encoder even though encoding was in table");
    304             return String();
    305         }
    306     }
    307 
    308     ErrorCallbackSetter callbackSetter(m_converterICU, stopOnError);
    309 
    310     StringBuilder result;
    311 
    312     UChar buffer[ConversionBufferSize];
    313     UChar* bufferLimit = buffer + ConversionBufferSize;
    314     const char* source = reinterpret_cast<const char*>(bytes);
    315     const char* sourceLimit = source + length;
    316     int32_t* offsets = NULL;
    317     UErrorCode err = U_ZERO_ERROR;
    318 
    319     do {
    320         int ucharsDecoded = decodeToBuffer(buffer, bufferLimit, source, sourceLimit, offsets, flush, err);
    321         result.append(buffer, ucharsDecoded);
    322     } while (err == U_BUFFER_OVERFLOW_ERROR);
    323 
    324     if (U_FAILURE(err)) {
    325         // flush the converter so it can be reused, and not be bothered by this error.
    326         do {
    327             decodeToBuffer(buffer, bufferLimit, source, sourceLimit, offsets, true, err);
    328         } while (source < sourceLimit);
    329         sawError = true;
    330     }
    331 
    332     String resultString = result.toString();
    333 
    334     // <http://bugs.webkit.org/show_bug.cgi?id=17014>
    335     // Simplified Chinese pages use the code A3A0 to mean "full-width space", but ICU decodes it as U+E5E5.
    336     if (strcmp(m_encoding.name(), "GBK") == 0 || strcasecmp(m_encoding.name(), "gb18030") == 0)
    337         resultString.replace(0xE5E5, ideographicSpace);
    338 
    339     return resultString;
    340 }
    341 
    342 // We need to apply these fallbacks ourselves as they are not currently supported by ICU and
    343 // they were provided by the old TEC encoding path. Needed to fix <rdar://problem/4708689>.
    344 static UChar fallbackForGBK(UChar32 character)
    345 {
    346     switch (character) {
    347     case 0x01F9:
    348         return 0xE7C8;
    349     case 0x1E3F:
    350         return 0xE7C7;
    351     case 0x22EF:
    352         return 0x2026;
    353     case 0x301C:
    354         return 0xFF5E;
    355     }
    356     return 0;
    357 }
    358 
    359 // Invalid character handler when writing escaped entities for unrepresentable
    360 // characters. See the declaration of TextCodec::encode for more.
    361 static void urlEscapedEntityCallback(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
    362     UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
    363 {
    364     if (reason == UCNV_UNASSIGNED) {
    365         *err = U_ZERO_ERROR;
    366 
    367         UnencodableReplacementArray entity;
    368         int entityLen = TextCodec::getUnencodableReplacement(codePoint, URLEncodedEntitiesForUnencodables, entity);
    369         ucnv_cbFromUWriteBytes(fromUArgs, entity, entityLen, 0, err);
    370     } else
    371         UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
    372 }
    373 
    374 // Substitutes special GBK characters, escaping all other unassigned entities.
    375 static void gbkCallbackEscape(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
    376     UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
    377 {
    378     UChar outChar;
    379     if (reason == UCNV_UNASSIGNED && (outChar = fallbackForGBK(codePoint))) {
    380         const UChar* source = &outChar;
    381         *err = U_ZERO_ERROR;
    382         ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
    383         return;
    384     }
    385     UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
    386 }
    387 
    388 // Combines both gbkUrlEscapedEntityCallback and GBK character substitution.
    389 static void gbkUrlEscapedEntityCallack(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
    390     UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
    391 {
    392     if (reason == UCNV_UNASSIGNED) {
    393         if (UChar outChar = fallbackForGBK(codePoint)) {
    394             const UChar* source = &outChar;
    395             *err = U_ZERO_ERROR;
    396             ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
    397             return;
    398         }
    399         urlEscapedEntityCallback(context, fromUArgs, codeUnits, length, codePoint, reason, err);
    400         return;
    401     }
    402     UCNV_FROM_U_CALLBACK_ESCAPE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
    403 }
    404 
    405 static void gbkCallbackSubstitute(const void* context, UConverterFromUnicodeArgs* fromUArgs, const UChar* codeUnits, int32_t length,
    406     UChar32 codePoint, UConverterCallbackReason reason, UErrorCode* err)
    407 {
    408     UChar outChar;
    409     if (reason == UCNV_UNASSIGNED && (outChar = fallbackForGBK(codePoint))) {
    410         const UChar* source = &outChar;
    411         *err = U_ZERO_ERROR;
    412         ucnv_cbFromUWriteUChars(fromUArgs, &source, source + 1, 0, err);
    413         return;
    414     }
    415     UCNV_FROM_U_CALLBACK_SUBSTITUTE(context, fromUArgs, codeUnits, length, codePoint, reason, err);
    416 }
    417 
    418 class TextCodecInput {
    419 public:
    420     TextCodecInput(const TextEncoding& encoding, const UChar* characters, size_t length)
    421         : m_begin(characters)
    422         , m_end(characters + length)
    423     {
    424         if (encoding.hasTrivialDisplayString())
    425             return;
    426         m_buffer.reserveInitialCapacity(length);
    427         m_buffer.append(characters, length);
    428         initalizeFromBuffer(encoding);
    429     }
    430 
    431     TextCodecInput(const TextEncoding& encoding, const LChar* characters, size_t length)
    432     {
    433         m_buffer.reserveInitialCapacity(length);
    434         for (size_t i = 0; i < length; ++i)
    435             m_buffer.append(characters[i]);
    436         initalizeFromBuffer(encoding);
    437     }
    438 
    439     const UChar* begin() const { return m_begin; }
    440     const UChar* end() const { return m_end; }
    441 
    442 private:
    443     void initalizeFromBuffer(const TextEncoding& encoding)
    444     {
    445         // FIXME: We should see if there is "force ASCII range" mode in ICU;
    446         // until then, we change the backslash into a yen sign.
    447         // Encoding will change the yen sign back into a backslash.
    448         encoding.displayBuffer(m_buffer.data(), m_buffer.size());
    449         m_begin = m_buffer.data();
    450         m_end = m_begin + m_buffer.size();
    451     }
    452 
    453     const UChar* m_begin;
    454     const UChar* m_end;
    455     Vector<UChar> m_buffer;
    456 };
    457 
    458 CString TextCodecICU::encodeInternal(const TextCodecInput& input, UnencodableHandling handling)
    459 {
    460     const UChar* source = input.begin();
    461     const UChar* end = input.end();
    462 
    463     UErrorCode err = U_ZERO_ERROR;
    464 
    465     switch (handling) {
    466         case QuestionMarksForUnencodables:
    467             ucnv_setSubstChars(m_converterICU, "?", 1, &err);
    468             ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkCallbackSubstitute : UCNV_FROM_U_CALLBACK_SUBSTITUTE, 0, 0, 0, &err);
    469             break;
    470         case EntitiesForUnencodables:
    471             ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkCallbackEscape : UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_XML_DEC, 0, 0, &err);
    472             break;
    473         case URLEncodedEntitiesForUnencodables:
    474             ucnv_setFromUCallBack(m_converterICU, m_needsGBKFallbacks ? gbkUrlEscapedEntityCallack : urlEscapedEntityCallback, 0, 0, 0, &err);
    475             break;
    476     }
    477 
    478     ASSERT(U_SUCCESS(err));
    479     if (U_FAILURE(err))
    480         return CString();
    481 
    482     Vector<char> result;
    483     size_t size = 0;
    484     do {
    485         char buffer[ConversionBufferSize];
    486         char* target = buffer;
    487         char* targetLimit = target + ConversionBufferSize;
    488         err = U_ZERO_ERROR;
    489         ucnv_fromUnicode(m_converterICU, &target, targetLimit, &source, end, 0, true, &err);
    490         size_t count = target - buffer;
    491         result.grow(size + count);
    492         memcpy(result.data() + size, buffer, count);
    493         size += count;
    494     } while (err == U_BUFFER_OVERFLOW_ERROR);
    495 
    496     return CString(result.data(), size);
    497 }
    498 
    499 template<typename CharType>
    500 CString TextCodecICU::encodeCommon(const CharType* characters, size_t length, UnencodableHandling handling)
    501 {
    502     if (!length)
    503         return "";
    504 
    505     if (!m_converterICU)
    506         createICUConverter();
    507     if (!m_converterICU)
    508         return CString();
    509 
    510     TextCodecInput input(m_encoding, characters, length);
    511     return encodeInternal(input, handling);
    512 }
    513 
    514 CString TextCodecICU::encode(const UChar* characters, size_t length, UnencodableHandling handling)
    515 {
    516     return encodeCommon(characters, length, handling);
    517 }
    518 
    519 CString TextCodecICU::encode(const LChar* characters, size_t length, UnencodableHandling handling)
    520 {
    521     return encodeCommon(characters, length, handling);
    522 }
    523 
    524 } // namespace WTF
    525