initial commit, 4.5 stable
Some checks failed
🔗 GHA / 📊 Static checks (push) Has been cancelled
🔗 GHA / 🤖 Android (push) Has been cancelled
🔗 GHA / 🍏 iOS (push) Has been cancelled
🔗 GHA / 🐧 Linux (push) Has been cancelled
🔗 GHA / 🍎 macOS (push) Has been cancelled
🔗 GHA / 🏁 Windows (push) Has been cancelled
🔗 GHA / 🌐 Web (push) Has been cancelled

This commit is contained in:
2025-09-16 20:46:46 -04:00
commit 9d30169a8d
13378 changed files with 7050105 additions and 0 deletions

313
thirdparty/icu4c/i18n/scriptset.cpp vendored Normal file
View File

@@ -0,0 +1,313 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2014, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
* scriptset.cpp
*
* created on: 2013 Jan 7
* created by: Andy Heninger
*/
#include "unicode/utypes.h"
#include "unicode/uchar.h"
#include "unicode/unistr.h"
#include "scriptset.h"
#include "uassert.h"
#include "cmemory.h"
U_NAMESPACE_BEGIN
//----------------------------------------------------------------------------
//
// ScriptSet implementation
//
//----------------------------------------------------------------------------
ScriptSet::ScriptSet() {
uprv_memset(bits, 0, sizeof(bits));
}
ScriptSet::~ScriptSet() {
}
ScriptSet::ScriptSet(const ScriptSet &other) {
*this = other;
}
ScriptSet & ScriptSet::operator =(const ScriptSet &other) {
uprv_memcpy(bits, other.bits, sizeof(bits));
return *this;
}
bool ScriptSet::operator == (const ScriptSet &other) const {
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
if (bits[i] != other.bits[i]) {
return false;
}
}
return true;
}
UBool ScriptSet::test(UScriptCode script, UErrorCode &status) const {
if (U_FAILURE(status)) {
return false;
}
if (script < 0 || static_cast<int32_t>(script) >= SCRIPT_LIMIT) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return false;
}
uint32_t index = script / 32;
uint32_t bit = 1 << (script & 31);
return ((bits[index] & bit) != 0);
}
ScriptSet &ScriptSet::set(UScriptCode script, UErrorCode &status) {
if (U_FAILURE(status)) {
return *this;
}
if (script < 0 || static_cast<int32_t>(script) >= SCRIPT_LIMIT) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return *this;
}
uint32_t index = script / 32;
uint32_t bit = 1 << (script & 31);
bits[index] |= bit;
return *this;
}
ScriptSet &ScriptSet::reset(UScriptCode script, UErrorCode &status) {
if (U_FAILURE(status)) {
return *this;
}
if (script < 0 || static_cast<int32_t>(script) >= SCRIPT_LIMIT) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return *this;
}
uint32_t index = script / 32;
uint32_t bit = 1 << (script & 31);
bits[index] &= ~bit;
return *this;
}
ScriptSet &ScriptSet::Union(const ScriptSet &other) {
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
bits[i] |= other.bits[i];
}
return *this;
}
ScriptSet &ScriptSet::intersect(const ScriptSet &other) {
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
bits[i] &= other.bits[i];
}
return *this;
}
ScriptSet &ScriptSet::intersect(UScriptCode script, UErrorCode &status) {
ScriptSet t;
t.set(script, status);
if (U_SUCCESS(status)) {
this->intersect(t);
}
return *this;
}
UBool ScriptSet::intersects(const ScriptSet &other) const {
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
if ((bits[i] & other.bits[i]) != 0) {
return true;
}
}
return false;
}
UBool ScriptSet::contains(const ScriptSet &other) const {
ScriptSet t(*this);
t.intersect(other);
return (t == other);
}
ScriptSet &ScriptSet::setAll() {
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
bits[i] = 0xffffffffu;
}
return *this;
}
ScriptSet &ScriptSet::resetAll() {
uprv_memset(bits, 0, sizeof(bits));
return *this;
}
int32_t ScriptSet::countMembers() const {
// This bit counter is good for sparse numbers of '1's, which is
// very much the case that we will usually have.
int32_t count = 0;
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
uint32_t x = bits[i];
while (x > 0) {
count++;
x &= (x - 1); // and off the least significant one bit.
}
}
return count;
}
int32_t ScriptSet::hashCode() const {
int32_t hash = 0;
for (int32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
hash ^= bits[i];
}
return hash;
}
int32_t ScriptSet::nextSetBit(int32_t fromIndex) const {
// TODO: Wants a better implementation.
if (fromIndex < 0) {
return -1;
}
UErrorCode status = U_ZERO_ERROR;
for (int32_t scriptIndex = fromIndex; scriptIndex < SCRIPT_LIMIT; scriptIndex++) {
if (test(static_cast<UScriptCode>(scriptIndex), status)) {
return scriptIndex;
}
}
return -1;
}
UBool ScriptSet::isEmpty() const {
for (uint32_t i=0; i<UPRV_LENGTHOF(bits); i++) {
if (bits[i] != 0) {
return false;
}
}
return true;
}
UnicodeString &ScriptSet::displayScripts(UnicodeString &dest) const {
UBool firstTime = true;
for (int32_t i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) {
if (!firstTime) {
dest.append(static_cast<char16_t>(0x20));
}
firstTime = false;
const char* scriptName = uscript_getShortName(static_cast<UScriptCode>(i));
dest.append(UnicodeString(scriptName, -1, US_INV));
}
return dest;
}
ScriptSet &ScriptSet::parseScripts(const UnicodeString &scriptString, UErrorCode &status) {
resetAll();
if (U_FAILURE(status)) {
return *this;
}
UnicodeString oneScriptName;
for (int32_t i=0; i<scriptString.length();) {
UChar32 c = scriptString.char32At(i);
i = scriptString.moveIndex32(i, 1);
if (!u_isUWhiteSpace(c)) {
oneScriptName.append(c);
if (i < scriptString.length()) {
continue;
}
}
if (oneScriptName.length() > 0) {
char buf[40];
oneScriptName.extract(0, oneScriptName.length(), buf, sizeof(buf)-1, US_INV);
buf[sizeof(buf)-1] = 0;
int32_t sc = u_getPropertyValueEnum(UCHAR_SCRIPT, buf);
if (sc == UCHAR_INVALID_CODE) {
status = U_ILLEGAL_ARGUMENT_ERROR;
} else {
this->set(static_cast<UScriptCode>(sc), status);
}
if (U_FAILURE(status)) {
return *this;
}
oneScriptName.remove();
}
}
return *this;
}
void ScriptSet::setScriptExtensions(UChar32 codePoint, UErrorCode& status) {
if (U_FAILURE(status)) { return; }
static const int32_t FIRST_GUESS_SCRIPT_CAPACITY = 20;
MaybeStackArray<UScriptCode,FIRST_GUESS_SCRIPT_CAPACITY> scripts;
UErrorCode internalStatus = U_ZERO_ERROR;
int32_t script_count = -1;
while (true) {
script_count = uscript_getScriptExtensions(
codePoint, scripts.getAlias(), scripts.getCapacity(), &internalStatus);
if (internalStatus == U_BUFFER_OVERFLOW_ERROR) {
// Need to allocate more space
if (scripts.resize(script_count) == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
internalStatus = U_ZERO_ERROR;
} else {
break;
}
}
// Check if we failed for some reason other than buffer overflow
if (U_FAILURE(internalStatus)) {
status = internalStatus;
return;
}
// Load the scripts into the ScriptSet and return
for (int32_t i = 0; i < script_count; i++) {
this->set(scripts[i], status);
if (U_FAILURE(status)) { return; }
}
}
U_NAMESPACE_END
U_CAPI UBool U_EXPORT2
uhash_equalsScriptSet(const UElement key1, const UElement key2) {
icu::ScriptSet *s1 = static_cast<icu::ScriptSet *>(key1.pointer);
icu::ScriptSet *s2 = static_cast<icu::ScriptSet *>(key2.pointer);
return (*s1 == *s2);
}
U_CAPI int32_t U_EXPORT2
uhash_compareScriptSet(UElement key0, UElement key1) {
icu::ScriptSet *s0 = static_cast<icu::ScriptSet *>(key0.pointer);
icu::ScriptSet *s1 = static_cast<icu::ScriptSet *>(key1.pointer);
int32_t diff = s0->countMembers() - s1->countMembers();
if (diff != 0) return diff;
int32_t i0 = s0->nextSetBit(0);
int32_t i1 = s1->nextSetBit(0);
while ((diff = i0-i1) == 0 && i0 > 0) {
i0 = s0->nextSetBit(i0+1);
i1 = s1->nextSetBit(i1+1);
}
return diff;
}
U_CAPI int32_t U_EXPORT2
uhash_hashScriptSet(const UElement key) {
icu::ScriptSet *s = static_cast<icu::ScriptSet *>(key.pointer);
return s->hashCode();
}
U_CAPI void U_EXPORT2
uhash_deleteScriptSet(void *obj) {
icu::ScriptSet *s = static_cast<icu::ScriptSet *>(obj);
delete s;
}

89
thirdparty/icu4c/i18n/scriptset.h vendored Normal file
View File

@@ -0,0 +1,89 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2013, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
* scriptset.h
*
* created on: 2013 Jan 7
* created by: Andy Heninger
*/
#ifndef __SCRIPTSET_H__
#define __SCRIPTSET_H__
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/uscript.h"
#include "uelement.h"
U_NAMESPACE_BEGIN
//-------------------------------------------------------------------------------
//
// ScriptSet - A bit set representing a set of scripts.
//
// This class was originally used exclusively with script sets appearing
// as part of the spoof check whole script confusable binary data. Its
// use has since become more general, but the continued use to wrap
// prebuilt binary data does constrain the design.
//
//-------------------------------------------------------------------------------
class U_I18N_API ScriptSet: public UMemory {
public:
static constexpr int32_t SCRIPT_LIMIT = 224; // multiple of 32!
ScriptSet();
ScriptSet(const ScriptSet &other);
~ScriptSet();
bool operator == (const ScriptSet &other) const;
bool operator != (const ScriptSet &other) const {return !(*this == other);}
ScriptSet & operator = (const ScriptSet &other);
UBool test(UScriptCode script, UErrorCode &status) const;
ScriptSet &Union(const ScriptSet &other);
ScriptSet &set(UScriptCode script, UErrorCode &status);
ScriptSet &reset(UScriptCode script, UErrorCode &status);
ScriptSet &intersect(const ScriptSet &other);
ScriptSet &intersect(UScriptCode script, UErrorCode &status);
UBool intersects(const ScriptSet &other) const; // Sets contain at least one script in common.
UBool contains(const ScriptSet &other) const; // All set bits in other are also set in this.
ScriptSet &setAll();
ScriptSet &resetAll();
int32_t countMembers() const;
int32_t hashCode() const;
int32_t nextSetBit(int32_t script) const;
UBool isEmpty() const;
UnicodeString &displayScripts(UnicodeString &dest) const; // append script names to dest string.
ScriptSet & parseScripts(const UnicodeString &scriptsString, UErrorCode &status); // Replaces ScriptSet contents.
// Wraps around UScript::getScriptExtensions() and adds the corresponding scripts to this instance.
void setScriptExtensions(UChar32 codePoint, UErrorCode& status);
private:
uint32_t bits[SCRIPT_LIMIT / 32];
};
U_NAMESPACE_END
U_CAPI int32_t U_EXPORT2
uhash_compareScriptSet(const UElement key1, const UElement key2);
U_CAPI int32_t U_EXPORT2
uhash_hashScriptSet(const UElement key);
U_CAPI void U_EXPORT2
uhash_deleteScriptSet(void *obj);
U_CAPI UBool U_EXPORT2
uhash_equalsScriptSet(const UElement key1, const UElement key2);
#endif // __SCRIPTSET_H_

65
thirdparty/icu4c/i18n/ucln_in.cpp vendored Normal file
View File

@@ -0,0 +1,65 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* *
* Copyright (C) 2001-2014, International Business Machines *
* Corporation and others. All Rights Reserved. *
* *
******************************************************************************
* file name: ucln_in.cpp
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2001July05
* created by: George Rhoten
*/
#include "ucln.h"
#include "ucln_in.h"
#include "mutex.h"
#include "uassert.h"
/** Auto-client for UCLN_I18N **/
#define UCLN_TYPE UCLN_I18N
#include "ucln_imp.h"
/* Leave this copyright notice here! It needs to go somewhere in this library. */
static const char copyright[] = U_COPYRIGHT_STRING;
static cleanupFunc *gCleanupFunctions[UCLN_I18N_COUNT];
static UBool U_CALLCONV i18n_cleanup()
{
int32_t libType = UCLN_I18N_START;
(void)copyright; /* Suppress unused variable warning with clang. */
while (++libType<UCLN_I18N_COUNT) {
if (gCleanupFunctions[libType])
{
gCleanupFunctions[libType]();
gCleanupFunctions[libType] = nullptr;
}
}
#if !UCLN_NO_AUTO_CLEANUP && (defined(UCLN_AUTO_ATEXIT) || defined(UCLN_AUTO_LOCAL))
ucln_unRegisterAutomaticCleanup();
#endif
return true;
}
void ucln_i18n_registerCleanup(ECleanupI18NType type,
cleanupFunc *func) {
U_ASSERT(UCLN_I18N_START < type && type < UCLN_I18N_COUNT);
{
icu::Mutex m; // See ticket 10295 for discussion.
ucln_registerCleanup(UCLN_I18N, i18n_cleanup);
if (UCLN_I18N_START < type && type < UCLN_I18N_COUNT) {
gCleanupFunctions[type] = func;
}
}
#if !UCLN_NO_AUTO_CLEANUP && (defined(UCLN_AUTO_ATEXIT) || defined(UCLN_AUTO_LOCAL))
ucln_registerAutomaticCleanup();
#endif
}

76
thirdparty/icu4c/i18n/ucln_in.h vendored Normal file
View File

@@ -0,0 +1,76 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* Copyright (C) 2001-2016, International Business Machines
* Corporation and others. All Rights Reserved.
******************************************************************************
* file name: ucln_in.h
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2001July05
* created by: George Rhoten
*/
#ifndef __UCLN_IN_H__
#define __UCLN_IN_H__
#include "unicode/utypes.h"
#include "ucln.h"
/*
Please keep the order of enums declared in same order
as the functions are suppose to be called.
It's usually best to have child dependencies called first. */
typedef enum ECleanupI18NType {
UCLN_I18N_START = -1,
UCLN_I18N_UNIT_EXTRAS,
UCLN_I18N_NUMBER_SKELETONS,
UCLN_I18N_CURRENCY_SPACING,
UCLN_I18N_SPOOF,
UCLN_I18N_SPOOFDATA,
UCLN_I18N_TRANSLITERATOR,
UCLN_I18N_REGEX,
UCLN_I18N_JAPANESE_CALENDAR,
UCLN_I18N_ISLAMIC_CALENDAR,
UCLN_I18N_CHINESE_CALENDAR,
UCLN_I18N_HEBREW_CALENDAR,
UCLN_I18N_ASTRO_CALENDAR,
UCLN_I18N_DANGI_CALENDAR,
UCLN_I18N_PERSIAN_CALENDAR,
UCLN_I18N_CALENDAR,
UCLN_I18N_TIMEZONEFORMAT,
UCLN_I18N_TZDBTIMEZONENAMES,
UCLN_I18N_TIMEZONEGENERICNAMES,
UCLN_I18N_TIMEZONENAMES,
UCLN_I18N_ZONEMETA,
UCLN_I18N_TIMEZONE,
UCLN_I18N_DIGITLIST,
UCLN_I18N_DECFMT,
UCLN_I18N_NUMFMT,
UCLN_I18N_ALLOWED_HOUR_FORMATS,
UCLN_I18N_DAYPERIODRULES,
UCLN_I18N_SMPDTFMT,
UCLN_I18N_USEARCH,
UCLN_I18N_COLLATOR,
UCLN_I18N_UCOL_RES,
UCLN_I18N_CSDET,
UCLN_I18N_COLLATION_ROOT,
UCLN_I18N_GENDERINFO,
UCLN_I18N_CDFINFO,
UCLN_I18N_REGION,
UCLN_I18N_LIST_FORMATTER,
UCLN_I18N_NUMSYS,
UCLN_I18N_MF2_UNISETS,
UCLN_I18N_COUNT /* This must be last */
} ECleanupI18NType;
/* Main library cleanup registration function. */
/* See common/ucln.h for details on adding a cleanup function. */
/* Note: the global mutex must not be held when calling this function. */
U_CFUNC void U_EXPORT2 ucln_i18n_registerCleanup(ECleanupI18NType type,
cleanupFunc *func);
#endif

1852
thirdparty/icu4c/i18n/unicode/uspoof.h vendored Normal file

File diff suppressed because it is too large Load Diff

925
thirdparty/icu4c/i18n/uspoof.cpp vendored Normal file
View File

@@ -0,0 +1,925 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
***************************************************************************
* Copyright (C) 2008-2015, International Business Machines Corporation
* and others. All Rights Reserved.
***************************************************************************
* file name: uspoof.cpp
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2008Feb13
* created by: Andy Heninger
*
* Unicode Spoof Detection
*/
#include "unicode/ubidi.h"
#include "unicode/utypes.h"
#include "unicode/normalizer2.h"
#include "unicode/uspoof.h"
#include "unicode/ustring.h"
#include "unicode/utf16.h"
#include "cmemory.h"
#include "cstring.h"
#include "mutex.h"
#include "scriptset.h"
#include "uassert.h"
#include "ucln_in.h"
#include "uspoof_impl.h"
#include "umutex.h"
#if !UCONFIG_NO_NORMALIZATION
U_NAMESPACE_USE
//
// Static Objects used by the spoof impl, their thread safe initialization and their cleanup.
//
static UnicodeSet *gInclusionSet = nullptr;
static UnicodeSet *gRecommendedSet = nullptr;
static const Normalizer2 *gNfdNormalizer = nullptr;
static UInitOnce gSpoofInitStaticsOnce {};
namespace {
UBool U_CALLCONV
uspoof_cleanup() {
delete gInclusionSet;
gInclusionSet = nullptr;
delete gRecommendedSet;
gRecommendedSet = nullptr;
gNfdNormalizer = nullptr;
gSpoofInitStaticsOnce.reset();
return true;
}
void U_CALLCONV initializeStatics(UErrorCode &status) {
gInclusionSet = new UnicodeSet();
gRecommendedSet = new UnicodeSet();
if (gInclusionSet == nullptr || gRecommendedSet == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
delete gInclusionSet;
gInclusionSet = nullptr;
delete gRecommendedSet;
gRecommendedSet = nullptr;
return;
}
gInclusionSet->applyIntPropertyValue(UCHAR_IDENTIFIER_TYPE, U_ID_TYPE_INCLUSION, status);
gRecommendedSet->applyIntPropertyValue(UCHAR_IDENTIFIER_TYPE, U_ID_TYPE_RECOMMENDED, status);
if (U_FAILURE(status)) {
delete gInclusionSet;
gInclusionSet = nullptr;
delete gRecommendedSet;
gRecommendedSet = nullptr;
return;
}
gInclusionSet->freeze();
gRecommendedSet->freeze();
gNfdNormalizer = Normalizer2::getNFDInstance(status);
ucln_i18n_registerCleanup(UCLN_I18N_SPOOF, uspoof_cleanup);
}
} // namespace
U_CFUNC void uspoof_internalInitStatics(UErrorCode *status) {
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
}
U_CAPI USpoofChecker * U_EXPORT2
uspoof_open(UErrorCode *status) {
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
if (U_FAILURE(*status)) {
return nullptr;
}
SpoofImpl *si = new SpoofImpl(*status);
if (si == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
if (U_FAILURE(*status)) {
delete si;
return nullptr;
}
return si->asUSpoofChecker();
}
U_CAPI USpoofChecker * U_EXPORT2
uspoof_openFromSerialized(const void *data, int32_t length, int32_t *pActualLength,
UErrorCode *status) {
if (U_FAILURE(*status)) {
return nullptr;
}
if (data == nullptr) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
if (U_FAILURE(*status))
{
return nullptr;
}
SpoofData *sd = new SpoofData(data, length, *status);
if (sd == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
if (U_FAILURE(*status)) {
delete sd;
return nullptr;
}
SpoofImpl *si = new SpoofImpl(sd, *status);
if (si == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
delete sd; // explicit delete as the destructor for si won't be called.
return nullptr;
}
if (U_FAILURE(*status)) {
delete si; // no delete for sd, as the si destructor will delete it.
return nullptr;
}
if (pActualLength != nullptr) {
*pActualLength = sd->size();
}
return si->asUSpoofChecker();
}
U_CAPI USpoofChecker * U_EXPORT2
uspoof_clone(const USpoofChecker *sc, UErrorCode *status) {
const SpoofImpl *src = SpoofImpl::validateThis(sc, *status);
if (src == nullptr) {
return nullptr;
}
SpoofImpl *result = new SpoofImpl(*src, *status); // copy constructor
if (result == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
if (U_FAILURE(*status)) {
delete result;
result = nullptr;
}
return result->asUSpoofChecker();
}
U_CAPI void U_EXPORT2
uspoof_close(USpoofChecker *sc) {
UErrorCode status = U_ZERO_ERROR;
SpoofImpl *This = SpoofImpl::validateThis(sc, status);
delete This;
}
U_CAPI void U_EXPORT2
uspoof_setChecks(USpoofChecker *sc, int32_t checks, UErrorCode *status) {
SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return;
}
// Verify that the requested checks are all ones (bits) that
// are acceptable, known values.
if (checks & ~(USPOOF_ALL_CHECKS | USPOOF_AUX_INFO)) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
This->fChecks = checks;
}
U_CAPI int32_t U_EXPORT2
uspoof_getChecks(const USpoofChecker *sc, UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return 0;
}
return This->fChecks;
}
U_CAPI void U_EXPORT2
uspoof_setRestrictionLevel(USpoofChecker *sc, URestrictionLevel restrictionLevel) {
UErrorCode status = U_ZERO_ERROR;
SpoofImpl *This = SpoofImpl::validateThis(sc, status);
if (This != nullptr) {
This->fRestrictionLevel = restrictionLevel;
This->fChecks |= USPOOF_RESTRICTION_LEVEL;
}
}
U_CAPI URestrictionLevel U_EXPORT2
uspoof_getRestrictionLevel(const USpoofChecker *sc) {
UErrorCode status = U_ZERO_ERROR;
const SpoofImpl *This = SpoofImpl::validateThis(sc, status);
if (This == nullptr) {
return USPOOF_UNRESTRICTIVE;
}
return This->fRestrictionLevel;
}
U_CAPI void U_EXPORT2
uspoof_setAllowedLocales(USpoofChecker *sc, const char *localesList, UErrorCode *status) {
SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return;
}
This->setAllowedLocales(localesList, *status);
}
U_CAPI const char * U_EXPORT2
uspoof_getAllowedLocales(USpoofChecker *sc, UErrorCode *status) {
SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return nullptr;
}
return This->getAllowedLocales(*status);
}
U_CAPI const USet * U_EXPORT2
uspoof_getAllowedChars(const USpoofChecker *sc, UErrorCode *status) {
const UnicodeSet *result = uspoof_getAllowedUnicodeSet(sc, status);
return result->toUSet();
}
U_CAPI const UnicodeSet * U_EXPORT2
uspoof_getAllowedUnicodeSet(const USpoofChecker *sc, UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return nullptr;
}
return This->fAllowedCharsSet;
}
U_CAPI void U_EXPORT2
uspoof_setAllowedChars(USpoofChecker *sc, const USet *chars, UErrorCode *status) {
const UnicodeSet *set = UnicodeSet::fromUSet(chars);
uspoof_setAllowedUnicodeSet(sc, set, status);
}
U_CAPI void U_EXPORT2
uspoof_setAllowedUnicodeSet(USpoofChecker *sc, const UnicodeSet *chars, UErrorCode *status) {
SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return;
}
if (chars->isBogus()) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
UnicodeSet *clonedSet = chars->clone();
if (clonedSet == nullptr || clonedSet->isBogus()) {
*status = U_MEMORY_ALLOCATION_ERROR;
return;
}
clonedSet->freeze();
delete This->fAllowedCharsSet;
This->fAllowedCharsSet = clonedSet;
This->fChecks |= USPOOF_CHAR_LIMIT;
}
U_CAPI int32_t U_EXPORT2
uspoof_check(const USpoofChecker *sc,
const char16_t *id, int32_t length,
int32_t *position,
UErrorCode *status) {
// Backwards compatibility:
if (position != nullptr) {
*position = 0;
}
// Delegate to uspoof_check2
return uspoof_check2(sc, id, length, nullptr, status);
}
U_CAPI int32_t U_EXPORT2
uspoof_check2(const USpoofChecker *sc,
const char16_t* id, int32_t length,
USpoofCheckResult* checkResult,
UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return 0;
}
if (length < -1) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString idStr((length == -1), id, length); // Aliasing constructor.
int32_t result = uspoof_check2UnicodeString(sc, idStr, checkResult, status);
return result;
}
U_CAPI int32_t U_EXPORT2
uspoof_checkUTF8(const USpoofChecker *sc,
const char *id, int32_t length,
int32_t *position,
UErrorCode *status) {
// Backwards compatibility:
if (position != nullptr) {
*position = 0;
}
// Delegate to uspoof_check2
return uspoof_check2UTF8(sc, id, length, nullptr, status);
}
U_CAPI int32_t U_EXPORT2
uspoof_check2UTF8(const USpoofChecker *sc,
const char *id, int32_t length,
USpoofCheckResult* checkResult,
UErrorCode *status) {
if (U_FAILURE(*status)) {
return 0;
}
UnicodeString idStr = UnicodeString::fromUTF8(StringPiece(id, length>=0 ? length : static_cast<int32_t>(uprv_strlen(id))));
int32_t result = uspoof_check2UnicodeString(sc, idStr, checkResult, status);
return result;
}
U_CAPI int32_t U_EXPORT2
uspoof_areConfusable(const USpoofChecker *sc,
const char16_t *id1, int32_t length1,
const char16_t *id2, int32_t length2,
UErrorCode *status) {
SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return 0;
}
if (length1 < -1 || length2 < -1) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString id1Str((length1==-1), id1, length1); // Aliasing constructor
UnicodeString id2Str((length2==-1), id2, length2); // Aliasing constructor
return uspoof_areConfusableUnicodeString(sc, id1Str, id2Str, status);
}
U_CAPI int32_t U_EXPORT2
uspoof_areConfusableUTF8(const USpoofChecker *sc,
const char *id1, int32_t length1,
const char *id2, int32_t length2,
UErrorCode *status) {
SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return 0;
}
if (length1 < -1 || length2 < -1) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString id1Str = UnicodeString::fromUTF8(StringPiece(id1, length1>=0? length1 : static_cast<int32_t>(uprv_strlen(id1))));
UnicodeString id2Str = UnicodeString::fromUTF8(StringPiece(id2, length2>=0? length2 : static_cast<int32_t>(uprv_strlen(id2))));
int32_t results = uspoof_areConfusableUnicodeString(sc, id1Str, id2Str, status);
return results;
}
U_CAPI int32_t U_EXPORT2
uspoof_areConfusableUnicodeString(const USpoofChecker *sc,
const icu::UnicodeString &id1,
const icu::UnicodeString &id2,
UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return 0;
}
//
// See section 4 of UAX 39 for the algorithm for checking whether two strings are confusable,
// and for definitions of the types (single, whole, mixed-script) of confusables.
// We only care about a few of the check flags. Ignore the others.
// If no tests relevant to this function have been specified, return an error.
// TODO: is this really the right thing to do? It's probably an error on the caller's part,
// but logically we would just return 0 (no error).
if ((This->fChecks & USPOOF_CONFUSABLE) == 0) {
*status = U_INVALID_STATE_ERROR;
return 0;
}
// Compute the skeletons and check for confusability.
UnicodeString id1Skeleton;
uspoof_getSkeletonUnicodeString(sc, 0 /* deprecated */, id1, id1Skeleton, status);
UnicodeString id2Skeleton;
uspoof_getSkeletonUnicodeString(sc, 0 /* deprecated */, id2, id2Skeleton, status);
if (U_FAILURE(*status)) { return 0; }
if (id1Skeleton != id2Skeleton) {
return 0;
}
// If we get here, the strings are confusable. Now we just need to set the flags for the appropriate classes
// of confusables according to UTS 39 section 4.
// Start by computing the resolved script sets of id1 and id2.
ScriptSet id1RSS;
This->getResolvedScriptSet(id1, id1RSS, *status);
ScriptSet id2RSS;
This->getResolvedScriptSet(id2, id2RSS, *status);
// Turn on all applicable flags
int32_t result = 0;
if (id1RSS.intersects(id2RSS)) {
result |= USPOOF_SINGLE_SCRIPT_CONFUSABLE;
} else {
result |= USPOOF_MIXED_SCRIPT_CONFUSABLE;
if (!id1RSS.isEmpty() && !id2RSS.isEmpty()) {
result |= USPOOF_WHOLE_SCRIPT_CONFUSABLE;
}
}
// Turn off flags that the user doesn't want
if ((This->fChecks & USPOOF_SINGLE_SCRIPT_CONFUSABLE) == 0) {
result &= ~USPOOF_SINGLE_SCRIPT_CONFUSABLE;
}
if ((This->fChecks & USPOOF_MIXED_SCRIPT_CONFUSABLE) == 0) {
result &= ~USPOOF_MIXED_SCRIPT_CONFUSABLE;
}
if ((This->fChecks & USPOOF_WHOLE_SCRIPT_CONFUSABLE) == 0) {
result &= ~USPOOF_WHOLE_SCRIPT_CONFUSABLE;
}
return result;
}
U_CAPI uint32_t U_EXPORT2 uspoof_areBidiConfusable(const USpoofChecker *sc, UBiDiDirection direction,
const char16_t *id1, int32_t length1,
const char16_t *id2, int32_t length2,
UErrorCode *status) {
UnicodeString id1Str((length1 == -1), id1, length1); // Aliasing constructor
UnicodeString id2Str((length2 == -1), id2, length2); // Aliasing constructor
if (id1Str.isBogus() || id2Str.isBogus()) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
return uspoof_areBidiConfusableUnicodeString(sc, direction, id1Str, id2Str, status);
}
U_CAPI uint32_t U_EXPORT2 uspoof_areBidiConfusableUTF8(const USpoofChecker *sc, UBiDiDirection direction,
const char *id1, int32_t length1, const char *id2,
int32_t length2, UErrorCode *status) {
if (length1 < -1 || length2 < -1) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString id1Str = UnicodeString::fromUTF8(
StringPiece(id1, length1 >= 0 ? length1 : static_cast<int32_t>(uprv_strlen(id1))));
UnicodeString id2Str = UnicodeString::fromUTF8(
StringPiece(id2, length2 >= 0 ? length2 : static_cast<int32_t>(uprv_strlen(id2))));
return uspoof_areBidiConfusableUnicodeString(sc, direction, id1Str, id2Str, status);
}
U_CAPI uint32_t U_EXPORT2 uspoof_areBidiConfusableUnicodeString(const USpoofChecker *sc,
UBiDiDirection direction,
const icu::UnicodeString &id1,
const icu::UnicodeString &id2,
UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return 0;
}
//
// See section 4 of UTS 39 for the algorithm for checking whether two strings are confusable,
// and for definitions of the types (single, whole, mixed-script) of confusables.
// We only care about a few of the check flags. Ignore the others.
// If no tests relevant to this function have been specified, return an error.
// TODO: is this really the right thing to do? It's probably an error on the caller's part,
// but logically we would just return 0 (no error).
if ((This->fChecks & USPOOF_CONFUSABLE) == 0) {
*status = U_INVALID_STATE_ERROR;
return 0;
}
// Compute the skeletons and check for confusability.
UnicodeString id1Skeleton;
uspoof_getBidiSkeletonUnicodeString(sc, direction, id1, id1Skeleton, status);
UnicodeString id2Skeleton;
uspoof_getBidiSkeletonUnicodeString(sc, direction, id2, id2Skeleton, status);
if (U_FAILURE(*status)) {
return 0;
}
if (id1Skeleton != id2Skeleton) {
return 0;
}
// If we get here, the strings are confusable. Now we just need to set the flags for the appropriate
// classes of confusables according to UTS 39 section 4. Start by computing the resolved script sets
// of id1 and id2.
ScriptSet id1RSS;
This->getResolvedScriptSet(id1, id1RSS, *status);
ScriptSet id2RSS;
This->getResolvedScriptSet(id2, id2RSS, *status);
// Turn on all applicable flags
uint32_t result = 0;
if (id1RSS.intersects(id2RSS)) {
result |= USPOOF_SINGLE_SCRIPT_CONFUSABLE;
} else {
result |= USPOOF_MIXED_SCRIPT_CONFUSABLE;
if (!id1RSS.isEmpty() && !id2RSS.isEmpty()) {
result |= USPOOF_WHOLE_SCRIPT_CONFUSABLE;
}
}
// Turn off flags that the user doesn't want
return result & This->fChecks;
}
U_CAPI int32_t U_EXPORT2
uspoof_checkUnicodeString(const USpoofChecker *sc,
const icu::UnicodeString &id,
int32_t *position,
UErrorCode *status) {
// Backwards compatibility:
if (position != nullptr) {
*position = 0;
}
// Delegate to uspoof_check2
return uspoof_check2UnicodeString(sc, id, nullptr, status);
}
namespace {
int32_t checkImpl(const SpoofImpl* This, const UnicodeString& id, CheckResult* checkResult, UErrorCode* status) {
U_ASSERT(This != nullptr);
U_ASSERT(checkResult != nullptr);
checkResult->clear();
int32_t result = 0;
if (0 != (This->fChecks & USPOOF_RESTRICTION_LEVEL)) {
URestrictionLevel idRestrictionLevel = This->getRestrictionLevel(id, *status);
if (idRestrictionLevel > This->fRestrictionLevel) {
result |= USPOOF_RESTRICTION_LEVEL;
}
checkResult->fRestrictionLevel = idRestrictionLevel;
}
if (0 != (This->fChecks & USPOOF_MIXED_NUMBERS)) {
UnicodeSet numerics;
This->getNumerics(id, numerics, *status);
if (numerics.size() > 1) {
result |= USPOOF_MIXED_NUMBERS;
}
checkResult->fNumerics = numerics; // UnicodeSet::operator=
}
if (0 != (This->fChecks & USPOOF_HIDDEN_OVERLAY)) {
int32_t index = This->findHiddenOverlay(id, *status);
if (index != -1) {
result |= USPOOF_HIDDEN_OVERLAY;
}
}
if (0 != (This->fChecks & USPOOF_CHAR_LIMIT)) {
int32_t i;
UChar32 c;
int32_t length = id.length();
for (i=0; i<length ;) {
c = id.char32At(i);
i += U16_LENGTH(c);
if (!This->fAllowedCharsSet->contains(c)) {
result |= USPOOF_CHAR_LIMIT;
break;
}
}
}
if (0 != (This->fChecks & USPOOF_INVISIBLE)) {
// This check needs to be done on NFD input
UnicodeString nfdText;
gNfdNormalizer->normalize(id, nfdText, *status);
int32_t nfdLength = nfdText.length();
// scan for more than one occurrence of the same non-spacing mark
// in a sequence of non-spacing marks.
int32_t i;
UChar32 c;
UChar32 firstNonspacingMark = 0;
UBool haveMultipleMarks = false;
UnicodeSet marksSeenSoFar; // Set of combining marks in a single combining sequence.
for (i=0; i<nfdLength ;) {
c = nfdText.char32At(i);
i += U16_LENGTH(c);
if (u_charType(c) != U_NON_SPACING_MARK) {
firstNonspacingMark = 0;
if (haveMultipleMarks) {
marksSeenSoFar.clear();
haveMultipleMarks = false;
}
continue;
}
if (firstNonspacingMark == 0) {
firstNonspacingMark = c;
continue;
}
if (!haveMultipleMarks) {
marksSeenSoFar.add(firstNonspacingMark);
haveMultipleMarks = true;
}
if (marksSeenSoFar.contains(c)) {
// report the error, and stop scanning.
// No need to find more than the first failure.
result |= USPOOF_INVISIBLE;
break;
}
marksSeenSoFar.add(c);
}
}
checkResult->fChecks = result;
return checkResult->toCombinedBitmask(This->fChecks);
}
} // namespace
U_CAPI int32_t U_EXPORT2
uspoof_check2UnicodeString(const USpoofChecker *sc,
const icu::UnicodeString &id,
USpoofCheckResult* checkResult,
UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
return false;
}
if (checkResult != nullptr) {
CheckResult* ThisCheckResult = CheckResult::validateThis(checkResult, *status);
if (ThisCheckResult == nullptr) {
return false;
}
return checkImpl(This, id, ThisCheckResult, status);
} else {
// Stack-allocate the checkResult since this method doesn't return it
CheckResult stackCheckResult;
return checkImpl(This, id, &stackCheckResult, status);
}
}
U_CAPI int32_t U_EXPORT2
uspoof_getSkeleton(const USpoofChecker *sc,
uint32_t type,
const char16_t *id, int32_t length,
char16_t *dest, int32_t destCapacity,
UErrorCode *status) {
SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return 0;
}
if (length<-1 || destCapacity<0 || (destCapacity==0 && dest!=nullptr)) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString idStr((length==-1), id, length); // Aliasing constructor
UnicodeString destStr;
uspoof_getSkeletonUnicodeString(sc, type, idStr, destStr, status);
destStr.extract(dest, destCapacity, *status);
return destStr.length();
}
U_CAPI int32_t U_EXPORT2 uspoof_getBidiSkeleton(const USpoofChecker *sc, UBiDiDirection direction,
const UChar *id, int32_t length, UChar *dest,
int32_t destCapacity, UErrorCode *status) {
UnicodeString idStr((length == -1), id, length); // Aliasing constructor
if (idStr.isBogus()) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString destStr;
uspoof_getBidiSkeletonUnicodeString(sc, direction, idStr, destStr, status);
return destStr.extract(dest, destCapacity, *status);
}
U_I18N_API UnicodeString &U_EXPORT2 uspoof_getBidiSkeletonUnicodeString(const USpoofChecker *sc,
UBiDiDirection direction,
const UnicodeString &id,
UnicodeString &dest,
UErrorCode *status) {
dest.remove();
if (direction != UBIDI_LTR && direction != UBIDI_RTL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return dest;
}
UBiDi *bidi = ubidi_open();
ubidi_setPara(bidi, id.getBuffer(), id.length(), direction,
/*embeddingLevels*/ nullptr, status);
if (U_FAILURE(*status)) {
ubidi_close(bidi);
return dest;
}
UnicodeString reordered;
int32_t const size = ubidi_getProcessedLength(bidi);
UChar* const reorderedBuffer = reordered.getBuffer(size);
if (reorderedBuffer == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
ubidi_close(bidi);
return dest;
}
ubidi_writeReordered(bidi, reorderedBuffer, size,
UBIDI_KEEP_BASE_COMBINING | UBIDI_DO_MIRRORING, status);
reordered.releaseBuffer(size);
ubidi_close(bidi);
if (U_FAILURE(*status)) {
return dest;
}
// The type parameter is deprecated since ICU 58; any number may be passed.
constexpr uint32_t deprecatedType = 58;
return uspoof_getSkeletonUnicodeString(sc, deprecatedType, reordered, dest, status);
}
U_I18N_API UnicodeString & U_EXPORT2
uspoof_getSkeletonUnicodeString(const USpoofChecker *sc,
uint32_t /*type*/,
const UnicodeString &id,
UnicodeString &dest,
UErrorCode *status) {
const SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return dest;
}
UnicodeString nfdId;
gNfdNormalizer->normalize(id, nfdId, *status);
// Apply the skeleton mapping to the NFD normalized input string
// Accumulate the skeleton, possibly unnormalized, in a UnicodeString.
int32_t inputIndex = 0;
UnicodeString skelStr;
int32_t normalizedLen = nfdId.length();
for (inputIndex=0; inputIndex < normalizedLen; ) {
UChar32 c = nfdId.char32At(inputIndex);
inputIndex += U16_LENGTH(c);
if (!u_hasBinaryProperty(c, UCHAR_DEFAULT_IGNORABLE_CODE_POINT)) {
This->fSpoofData->confusableLookup(c, skelStr);
}
}
gNfdNormalizer->normalize(skelStr, dest, *status);
return dest;
}
U_CAPI int32_t U_EXPORT2 uspoof_getSkeletonUTF8(const USpoofChecker *sc, uint32_t type, const char *id,
int32_t length, char *dest, int32_t destCapacity,
UErrorCode *status) {
SpoofImpl::validateThis(sc, *status);
if (U_FAILURE(*status)) {
return 0;
}
if (length<-1 || destCapacity<0 || (destCapacity==0 && dest!=nullptr)) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString srcStr = UnicodeString::fromUTF8(
StringPiece(id, length >= 0 ? length : static_cast<int32_t>(uprv_strlen(id))));
UnicodeString destStr;
uspoof_getSkeletonUnicodeString(sc, type, srcStr, destStr, status);
if (U_FAILURE(*status)) {
return 0;
}
int32_t lengthInUTF8 = 0;
u_strToUTF8(dest, destCapacity, &lengthInUTF8, destStr.getBuffer(), destStr.length(), status);
return lengthInUTF8;
}
U_CAPI int32_t U_EXPORT2 uspoof_getBidiSkeletonUTF8(const USpoofChecker *sc, UBiDiDirection direction,
const char *id, int32_t length, char *dest,
int32_t destCapacity, UErrorCode *status) {
if (length < -1) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
UnicodeString srcStr = UnicodeString::fromUTF8(
StringPiece(id, length >= 0 ? length : static_cast<int32_t>(uprv_strlen(id))));
UnicodeString destStr;
uspoof_getBidiSkeletonUnicodeString(sc, direction, srcStr, destStr, status);
if (U_FAILURE(*status)) {
return 0;
}
int32_t lengthInUTF8 = 0;
u_strToUTF8(dest, destCapacity, &lengthInUTF8, destStr.getBuffer(), destStr.length(), status);
return lengthInUTF8;
}
U_CAPI int32_t U_EXPORT2
uspoof_serialize(USpoofChecker *sc,void *buf, int32_t capacity, UErrorCode *status) {
SpoofImpl *This = SpoofImpl::validateThis(sc, *status);
if (This == nullptr) {
U_ASSERT(U_FAILURE(*status));
return 0;
}
return This->fSpoofData->serialize(buf, capacity, *status);
}
U_CAPI const USet * U_EXPORT2
uspoof_getInclusionSet(UErrorCode *status) {
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
return gInclusionSet->toUSet();
}
U_CAPI const USet * U_EXPORT2
uspoof_getRecommendedSet(UErrorCode *status) {
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
return gRecommendedSet->toUSet();
}
U_I18N_API const UnicodeSet * U_EXPORT2
uspoof_getInclusionUnicodeSet(UErrorCode *status) {
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
return gInclusionSet;
}
U_I18N_API const UnicodeSet * U_EXPORT2
uspoof_getRecommendedUnicodeSet(UErrorCode *status) {
umtx_initOnce(gSpoofInitStaticsOnce, &initializeStatics, *status);
return gRecommendedSet;
}
//------------------
// CheckResult APIs
//------------------
U_CAPI USpoofCheckResult* U_EXPORT2
uspoof_openCheckResult(UErrorCode *status) {
CheckResult* checkResult = new CheckResult();
if (checkResult == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
return checkResult->asUSpoofCheckResult();
}
U_CAPI void U_EXPORT2
uspoof_closeCheckResult(USpoofCheckResult* checkResult) {
UErrorCode status = U_ZERO_ERROR;
CheckResult* This = CheckResult::validateThis(checkResult, status);
delete This;
}
U_CAPI int32_t U_EXPORT2
uspoof_getCheckResultChecks(const USpoofCheckResult *checkResult, UErrorCode *status) {
const CheckResult* This = CheckResult::validateThis(checkResult, *status);
if (U_FAILURE(*status)) { return 0; }
return This->fChecks;
}
U_CAPI URestrictionLevel U_EXPORT2
uspoof_getCheckResultRestrictionLevel(const USpoofCheckResult *checkResult, UErrorCode *status) {
const CheckResult* This = CheckResult::validateThis(checkResult, *status);
if (U_FAILURE(*status)) { return USPOOF_UNRESTRICTIVE; }
return This->fRestrictionLevel;
}
U_CAPI const USet* U_EXPORT2
uspoof_getCheckResultNumerics(const USpoofCheckResult *checkResult, UErrorCode *status) {
const CheckResult* This = CheckResult::validateThis(checkResult, *status);
if (U_FAILURE(*status)) { return nullptr; }
return This->fNumerics.toUSet();
}
#endif // !UCONFIG_NO_NORMALIZATION

959
thirdparty/icu4c/i18n/uspoof_impl.cpp vendored Normal file
View File

@@ -0,0 +1,959 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2008-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*/
#include "unicode/utypes.h"
#include "unicode/uspoof.h"
#include "unicode/uchar.h"
#include "unicode/uniset.h"
#include "unicode/utf16.h"
#include "utrie2.h"
#include "cmemory.h"
#include "cstring.h"
#include "scriptset.h"
#include "umutex.h"
#include "udataswp.h"
#include "uassert.h"
#include "ucln_in.h"
#include "uspoof_impl.h"
#if !UCONFIG_NO_NORMALIZATION
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SpoofImpl)
SpoofImpl::SpoofImpl(SpoofData *data, UErrorCode& status) {
construct(status);
fSpoofData = data;
}
SpoofImpl::SpoofImpl(UErrorCode& status) {
construct(status);
// TODO: Call this method where it is actually needed, instead of in the
// constructor, to allow for lazy data loading. See #12696.
fSpoofData = SpoofData::getDefault(status);
}
SpoofImpl::SpoofImpl() {
UErrorCode status = U_ZERO_ERROR;
construct(status);
// TODO: Call this method where it is actually needed, instead of in the
// constructor, to allow for lazy data loading. See #12696.
fSpoofData = SpoofData::getDefault(status);
}
void SpoofImpl::construct(UErrorCode& status) {
fChecks = USPOOF_ALL_CHECKS;
fSpoofData = nullptr;
fAllowedCharsSet = nullptr;
fAllowedLocales = nullptr;
fRestrictionLevel = USPOOF_HIGHLY_RESTRICTIVE;
if (U_FAILURE(status)) { return; }
UnicodeSet *allowedCharsSet = new UnicodeSet(0, 0x10ffff);
fAllowedCharsSet = allowedCharsSet;
fAllowedLocales = uprv_strdup("");
if (fAllowedCharsSet == nullptr || fAllowedLocales == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
allowedCharsSet->freeze();
}
// Copy Constructor, used by the user level clone() function.
SpoofImpl::SpoofImpl(const SpoofImpl &src, UErrorCode &status) :
fChecks(USPOOF_ALL_CHECKS), fSpoofData(nullptr), fAllowedCharsSet(nullptr) ,
fAllowedLocales(nullptr) {
if (U_FAILURE(status)) {
return;
}
fChecks = src.fChecks;
if (src.fSpoofData != nullptr) {
fSpoofData = src.fSpoofData->addReference();
}
fAllowedCharsSet = src.fAllowedCharsSet->clone();
fAllowedLocales = uprv_strdup(src.fAllowedLocales);
if (fAllowedCharsSet == nullptr || fAllowedLocales == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
}
fRestrictionLevel = src.fRestrictionLevel;
}
SpoofImpl::~SpoofImpl() {
if (fSpoofData != nullptr) {
fSpoofData->removeReference(); // Will delete if refCount goes to zero.
}
delete fAllowedCharsSet;
uprv_free((void *)fAllowedLocales);
}
// Cast this instance as a USpoofChecker for the C API.
USpoofChecker *SpoofImpl::asUSpoofChecker() {
return exportForC();
}
//
// Incoming parameter check on Status and the SpoofChecker object
// received from the C API.
//
const SpoofImpl *SpoofImpl::validateThis(const USpoofChecker *sc, UErrorCode &status) {
const auto* This = validate(sc, status);
if (U_FAILURE(status)) {
return nullptr;
}
if (This->fSpoofData != nullptr && !This->fSpoofData->validateDataVersion(status)) {
return nullptr;
}
return This;
}
SpoofImpl *SpoofImpl::validateThis(USpoofChecker *sc, UErrorCode &status) {
return const_cast<SpoofImpl *>
(SpoofImpl::validateThis(const_cast<const USpoofChecker *>(sc), status));
}
void SpoofImpl::setAllowedLocales(const char *localesList, UErrorCode &status) {
UnicodeSet allowedChars;
UnicodeSet *tmpSet = nullptr;
const char *locStart = localesList;
const char *locEnd = nullptr;
const char *localesListEnd = localesList + uprv_strlen(localesList);
int32_t localeListCount = 0; // Number of locales provided by caller.
// Loop runs once per locale from the localesList, a comma separated list of locales.
do {
locEnd = uprv_strchr(locStart, ',');
if (locEnd == nullptr) {
locEnd = localesListEnd;
}
while (*locStart == ' ') {
locStart++;
}
const char *trimmedEnd = locEnd-1;
while (trimmedEnd > locStart && *trimmedEnd == ' ') {
trimmedEnd--;
}
if (trimmedEnd <= locStart) {
break;
}
const char* locale = uprv_strndup(locStart, static_cast<int32_t>(trimmedEnd + 1 - locStart));
localeListCount++;
// We have one locale from the locales list.
// Add the script chars for this locale to the accumulating set of allowed chars.
// If the locale is no good, we will be notified back via status.
addScriptChars(locale, &allowedChars, status);
uprv_free((void *)locale);
if (U_FAILURE(status)) {
break;
}
locStart = locEnd + 1;
} while (locStart < localesListEnd);
// If our caller provided an empty list of locales, we disable the allowed characters checking
if (localeListCount == 0) {
uprv_free((void *)fAllowedLocales);
fAllowedLocales = uprv_strdup("");
tmpSet = new UnicodeSet(0, 0x10ffff);
if (fAllowedLocales == nullptr || tmpSet == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
tmpSet->freeze();
delete fAllowedCharsSet;
fAllowedCharsSet = tmpSet;
fChecks &= ~USPOOF_CHAR_LIMIT;
return;
}
// Add all common and inherited characters to the set of allowed chars.
UnicodeSet tempSet;
tempSet.applyIntPropertyValue(UCHAR_SCRIPT, USCRIPT_COMMON, status);
allowedChars.addAll(tempSet);
tempSet.applyIntPropertyValue(UCHAR_SCRIPT, USCRIPT_INHERITED, status);
allowedChars.addAll(tempSet);
// If anything went wrong, we bail out without changing
// the state of the spoof checker.
if (U_FAILURE(status)) {
return;
}
// Store the updated spoof checker state.
tmpSet = allowedChars.clone();
const char *tmpLocalesList = uprv_strdup(localesList);
if (tmpSet == nullptr || tmpLocalesList == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
uprv_free((void *)fAllowedLocales);
fAllowedLocales = tmpLocalesList;
tmpSet->freeze();
delete fAllowedCharsSet;
fAllowedCharsSet = tmpSet;
fChecks |= USPOOF_CHAR_LIMIT;
}
const char * SpoofImpl::getAllowedLocales(UErrorCode &/*status*/) {
return fAllowedLocales;
}
// Given a locale (a language), add all the characters from all of the scripts used with that language
// to the allowedChars UnicodeSet
void SpoofImpl::addScriptChars(const char *locale, UnicodeSet *allowedChars, UErrorCode &status) {
UScriptCode scripts[30];
int32_t numScripts = uscript_getCode(locale, scripts, UPRV_LENGTHOF(scripts), &status);
if (U_FAILURE(status)) {
return;
}
if (status == U_USING_DEFAULT_WARNING) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
UnicodeSet tmpSet;
int32_t i;
for (i=0; i<numScripts; i++) {
tmpSet.applyIntPropertyValue(UCHAR_SCRIPT, scripts[i], status);
allowedChars->addAll(tmpSet);
}
}
// Computes the augmented script set for a code point, according to UTS 39 section 5.1.
void SpoofImpl::getAugmentedScriptSet(UChar32 codePoint, ScriptSet& result, UErrorCode& status) {
result.resetAll();
result.setScriptExtensions(codePoint, status);
if (U_FAILURE(status)) { return; }
// Section 5.1 step 1
if (result.test(USCRIPT_HAN, status)) {
result.set(USCRIPT_HAN_WITH_BOPOMOFO, status);
result.set(USCRIPT_JAPANESE, status);
result.set(USCRIPT_KOREAN, status);
}
if (result.test(USCRIPT_HIRAGANA, status)) {
result.set(USCRIPT_JAPANESE, status);
}
if (result.test(USCRIPT_KATAKANA, status)) {
result.set(USCRIPT_JAPANESE, status);
}
if (result.test(USCRIPT_HANGUL, status)) {
result.set(USCRIPT_KOREAN, status);
}
if (result.test(USCRIPT_BOPOMOFO, status)) {
result.set(USCRIPT_HAN_WITH_BOPOMOFO, status);
}
// Section 5.1 step 2
if (result.test(USCRIPT_COMMON, status) || result.test(USCRIPT_INHERITED, status)) {
result.setAll();
}
}
// Computes the resolved script set for a string, according to UTS 39 section 5.1.
void SpoofImpl::getResolvedScriptSet(const UnicodeString& input, ScriptSet& result, UErrorCode& status) const {
getResolvedScriptSetWithout(input, USCRIPT_CODE_LIMIT, result, status);
}
// Computes the resolved script set for a string, omitting characters having the specified script.
// If USCRIPT_CODE_LIMIT is passed as the second argument, all characters are included.
void SpoofImpl::getResolvedScriptSetWithout(const UnicodeString& input, UScriptCode script, ScriptSet& result, UErrorCode& status) const {
result.setAll();
ScriptSet temp;
UChar32 codePoint;
for (int32_t i = 0; i < input.length(); i += U16_LENGTH(codePoint)) {
codePoint = input.char32At(i);
// Compute the augmented script set for the character
getAugmentedScriptSet(codePoint, temp, status);
if (U_FAILURE(status)) { return; }
// Intersect the augmented script set with the resolved script set, but only if the character doesn't
// have the script specified in the function call
if (script == USCRIPT_CODE_LIMIT || !temp.test(script, status)) {
result.intersect(temp);
}
}
}
// Computes the set of numerics for a string, according to UTS 39 section 5.3.
void SpoofImpl::getNumerics(const UnicodeString& input, UnicodeSet& result, UErrorCode& /*status*/) const {
result.clear();
UChar32 codePoint;
for (int32_t i = 0; i < input.length(); i += U16_LENGTH(codePoint)) {
codePoint = input.char32At(i);
// Store a representative character for each kind of decimal digit
if (u_charType(codePoint) == U_DECIMAL_DIGIT_NUMBER) {
// Store the zero character as a representative for comparison.
// Unicode guarantees it is codePoint - value
result.add(codePoint - static_cast<UChar32>(u_getNumericValue(codePoint)));
}
}
}
// Computes the restriction level of a string, according to UTS 39 section 5.2.
URestrictionLevel SpoofImpl::getRestrictionLevel(const UnicodeString& input, UErrorCode& status) const {
// Section 5.2 step 1:
if (!fAllowedCharsSet->containsAll(input)) {
return USPOOF_UNRESTRICTIVE;
}
// Section 5.2 step 2
// Java use a static UnicodeSet for this test. In C++, avoid the static variable
// and just do a simple for loop.
UBool allASCII = true;
for (int32_t i=0, length=input.length(); i<length; i++) {
if (input.charAt(i) > 0x7f) {
allASCII = false;
break;
}
}
if (allASCII) {
return USPOOF_ASCII;
}
// Section 5.2 steps 3:
ScriptSet resolvedScriptSet;
getResolvedScriptSet(input, resolvedScriptSet, status);
if (U_FAILURE(status)) { return USPOOF_UNRESTRICTIVE; }
// Section 5.2 step 4:
if (!resolvedScriptSet.isEmpty()) {
return USPOOF_SINGLE_SCRIPT_RESTRICTIVE;
}
// Section 5.2 step 5:
ScriptSet resolvedNoLatn;
getResolvedScriptSetWithout(input, USCRIPT_LATIN, resolvedNoLatn, status);
if (U_FAILURE(status)) { return USPOOF_UNRESTRICTIVE; }
// Section 5.2 step 6:
if (resolvedNoLatn.test(USCRIPT_HAN_WITH_BOPOMOFO, status)
|| resolvedNoLatn.test(USCRIPT_JAPANESE, status)
|| resolvedNoLatn.test(USCRIPT_KOREAN, status)) {
return USPOOF_HIGHLY_RESTRICTIVE;
}
// Section 5.2 step 7:
if (!resolvedNoLatn.isEmpty()
&& !resolvedNoLatn.test(USCRIPT_CYRILLIC, status)
&& !resolvedNoLatn.test(USCRIPT_GREEK, status)
&& !resolvedNoLatn.test(USCRIPT_CHEROKEE, status)) {
return USPOOF_MODERATELY_RESTRICTIVE;
}
// Section 5.2 step 8:
return USPOOF_MINIMALLY_RESTRICTIVE;
}
int32_t SpoofImpl::findHiddenOverlay(const UnicodeString& input, UErrorCode&) const {
bool sawLeadCharacter = false;
for (int32_t i=0; i<input.length();) {
UChar32 cp = input.char32At(i);
if (sawLeadCharacter && cp == 0x0307) {
return i;
}
uint8_t combiningClass = u_getCombiningClass(cp);
// Skip over characters except for those with combining class 0 (non-combining characters) or with
// combining class 230 (same class as U+0307)
U_ASSERT(u_getCombiningClass(0x0307) == 230);
if (combiningClass == 0 || combiningClass == 230) {
sawLeadCharacter = isIllegalCombiningDotLeadCharacter(cp);
}
i += U16_LENGTH(cp);
}
return -1;
}
static inline bool isIllegalCombiningDotLeadCharacterNoLookup(UChar32 cp) {
return cp == u'i' || cp == u'j' || cp == u'ı' || cp == u'ȷ' || cp == u'l' ||
u_hasBinaryProperty(cp, UCHAR_SOFT_DOTTED);
}
bool SpoofImpl::isIllegalCombiningDotLeadCharacter(UChar32 cp) const {
if (isIllegalCombiningDotLeadCharacterNoLookup(cp)) {
return true;
}
UnicodeString skelStr;
fSpoofData->confusableLookup(cp, skelStr);
UChar32 finalCp = skelStr.char32At(skelStr.moveIndex32(skelStr.length(), -1));
if (finalCp != cp && isIllegalCombiningDotLeadCharacterNoLookup(finalCp)) {
return true;
}
return false;
}
// Convert a text format hex number. Utility function used by builder code. Static.
// Input: char16_t *string text. Output: a UChar32
// Input has been pre-checked, and will have no non-hex chars.
// The number must fall in the code point range of 0..0x10ffff
// Static Function.
UChar32 SpoofImpl::ScanHex(const char16_t *s, int32_t start, int32_t limit, UErrorCode &status) {
if (U_FAILURE(status)) {
return 0;
}
U_ASSERT(limit-start > 0);
uint32_t val = 0;
int i;
for (i=start; i<limit; i++) {
int digitVal = s[i] - 0x30;
if (digitVal>9) {
digitVal = 0xa + (s[i] - 0x41); // Upper Case 'A'
}
if (digitVal>15) {
digitVal = 0xa + (s[i] - 0x61); // Lower Case 'a'
}
U_ASSERT(digitVal <= 0xf);
val <<= 4;
val += digitVal;
}
if (val > 0x10ffff) {
status = U_PARSE_ERROR;
val = 0;
}
return static_cast<UChar32>(val);
}
//-----------------------------------------
//
// class CheckResult Implementation
//
//-----------------------------------------
CheckResult::CheckResult() {
clear();
}
USpoofCheckResult* CheckResult::asUSpoofCheckResult() {
return exportForC();
}
//
// Incoming parameter check on Status and the CheckResult object
// received from the C API.
//
const CheckResult* CheckResult::validateThis(const USpoofCheckResult *ptr, UErrorCode &status) {
return validate(ptr, status);
}
CheckResult* CheckResult::validateThis(USpoofCheckResult *ptr, UErrorCode &status) {
return validate(ptr, status);
}
void CheckResult::clear() {
fChecks = 0;
fNumerics.clear();
fRestrictionLevel = USPOOF_UNDEFINED_RESTRICTIVE;
}
int32_t CheckResult::toCombinedBitmask(int32_t enabledChecks) {
if ((enabledChecks & USPOOF_AUX_INFO) != 0 && fRestrictionLevel != USPOOF_UNDEFINED_RESTRICTIVE) {
return fChecks | fRestrictionLevel;
} else {
return fChecks;
}
}
CheckResult::~CheckResult() {
}
//----------------------------------------------------------------------------------------------
//
// class SpoofData Implementation
//
//----------------------------------------------------------------------------------------------
UBool SpoofData::validateDataVersion(UErrorCode &status) const {
if (U_FAILURE(status) ||
fRawData == nullptr ||
fRawData->fMagic != USPOOF_MAGIC ||
fRawData->fFormatVersion[0] != USPOOF_CONFUSABLE_DATA_FORMAT_VERSION ||
fRawData->fFormatVersion[1] != 0 ||
fRawData->fFormatVersion[2] != 0 ||
fRawData->fFormatVersion[3] != 0) {
status = U_INVALID_FORMAT_ERROR;
return false;
}
return true;
}
static UBool U_CALLCONV
spoofDataIsAcceptable(void *context,
const char * /* type */, const char * /*name*/,
const UDataInfo *pInfo) {
if(
pInfo->size >= 20 &&
pInfo->isBigEndian == U_IS_BIG_ENDIAN &&
pInfo->charsetFamily == U_CHARSET_FAMILY &&
pInfo->dataFormat[0] == 0x43 && // dataFormat="Cfu "
pInfo->dataFormat[1] == 0x66 &&
pInfo->dataFormat[2] == 0x75 &&
pInfo->dataFormat[3] == 0x20 &&
pInfo->formatVersion[0] == USPOOF_CONFUSABLE_DATA_FORMAT_VERSION
) {
UVersionInfo *version = static_cast<UVersionInfo *>(context);
if(version != nullptr) {
uprv_memcpy(version, pInfo->dataVersion, 4);
}
return true;
} else {
return false;
}
}
// Methods for the loading of the default confusables data file. The confusable
// data is loaded only when it is needed.
//
// SpoofData::getDefault() - Return the default confusables data, and call the
// initOnce() if it is not available. Adds a reference
// to the SpoofData that the caller is responsible for
// decrementing when they are done with the data.
//
// uspoof_loadDefaultData - Called once, from initOnce(). The resulting SpoofData
// is shared by all spoof checkers using the default data.
//
// uspoof_cleanupDefaultData - Called during cleanup.
//
static UInitOnce gSpoofInitDefaultOnce {};
static SpoofData* gDefaultSpoofData;
static UBool U_CALLCONV
uspoof_cleanupDefaultData() {
if (gDefaultSpoofData) {
// Will delete, assuming all user-level spoof checkers were closed.
gDefaultSpoofData->removeReference();
gDefaultSpoofData = nullptr;
gSpoofInitDefaultOnce.reset();
}
return true;
}
static void U_CALLCONV uspoof_loadDefaultData(UErrorCode& status) {
UDataMemory *udm = udata_openChoice(nullptr, "cfu", "confusables",
spoofDataIsAcceptable,
nullptr, // context, would receive dataVersion if supplied.
&status);
if (U_FAILURE(status)) { return; }
gDefaultSpoofData = new SpoofData(udm, status);
if (U_FAILURE(status)) {
delete gDefaultSpoofData;
gDefaultSpoofData = nullptr;
return;
}
if (gDefaultSpoofData == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
ucln_i18n_registerCleanup(UCLN_I18N_SPOOFDATA, uspoof_cleanupDefaultData);
}
SpoofData* SpoofData::getDefault(UErrorCode& status) {
umtx_initOnce(gSpoofInitDefaultOnce, &uspoof_loadDefaultData, status);
if (U_FAILURE(status)) { return nullptr; }
gDefaultSpoofData->addReference();
return gDefaultSpoofData;
}
SpoofData::SpoofData(UDataMemory *udm, UErrorCode &status)
{
reset();
if (U_FAILURE(status)) {
return;
}
fUDM = udm;
// fRawData is non-const because it may be constructed by the data builder.
fRawData = reinterpret_cast<SpoofDataHeader *>(
const_cast<void *>(udata_getMemory(udm)));
validateDataVersion(status);
initPtrs(status);
}
SpoofData::SpoofData(const void *data, int32_t length, UErrorCode &status)
{
reset();
if (U_FAILURE(status)) {
return;
}
if (static_cast<size_t>(length) < sizeof(SpoofDataHeader)) {
status = U_INVALID_FORMAT_ERROR;
return;
}
if (data == nullptr) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
void *ncData = const_cast<void *>(data);
fRawData = static_cast<SpoofDataHeader *>(ncData);
if (length < fRawData->fLength) {
status = U_INVALID_FORMAT_ERROR;
return;
}
validateDataVersion(status);
initPtrs(status);
}
// Spoof Data constructor for use from data builder.
// Initializes a new, empty data area that will be populated later.
SpoofData::SpoofData(UErrorCode &status) {
reset();
if (U_FAILURE(status)) {
return;
}
fDataOwned = true;
// The spoof header should already be sized to be a multiple of 16 bytes.
// Just in case it's not, round it up.
uint32_t initialSize = (sizeof(SpoofDataHeader) + 15) & ~15;
U_ASSERT(initialSize == sizeof(SpoofDataHeader));
fRawData = static_cast<SpoofDataHeader *>(uprv_malloc(initialSize));
fMemLimit = initialSize;
if (fRawData == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
uprv_memset(fRawData, 0, initialSize);
fRawData->fMagic = USPOOF_MAGIC;
fRawData->fFormatVersion[0] = USPOOF_CONFUSABLE_DATA_FORMAT_VERSION;
fRawData->fFormatVersion[1] = 0;
fRawData->fFormatVersion[2] = 0;
fRawData->fFormatVersion[3] = 0;
initPtrs(status);
}
// reset() - initialize all fields.
// Should be updated if any new fields are added.
// Called by constructors to put things in a known initial state.
void SpoofData::reset() {
fRawData = nullptr;
fDataOwned = false;
fUDM = nullptr;
fMemLimit = 0;
fRefCount = 1;
fCFUKeys = nullptr;
fCFUValues = nullptr;
fCFUStrings = nullptr;
}
// SpoofData::initPtrs()
// Initialize the pointers to the various sections of the raw data.
//
// This function is used both during the Trie building process (multiple
// times, as the individual data sections are added), and
// during the opening of a Spoof Checker from prebuilt data.
//
// The pointers for non-existent data sections (identified by an offset of 0)
// are set to nullptr.
//
// Note: During building the data, adding each new data section
// reallocs the raw data area, which likely relocates it, which
// in turn requires reinitializing all of the pointers into it, hence
// multiple calls to this function during building.
//
void SpoofData::initPtrs(UErrorCode &status) {
fCFUKeys = nullptr;
fCFUValues = nullptr;
fCFUStrings = nullptr;
if (U_FAILURE(status)) {
return;
}
if (fRawData->fCFUKeys != 0) {
fCFUKeys = reinterpret_cast<int32_t*>(reinterpret_cast<char*>(fRawData) + fRawData->fCFUKeys);
}
if (fRawData->fCFUStringIndex != 0) {
fCFUValues = reinterpret_cast<uint16_t*>(reinterpret_cast<char*>(fRawData) + fRawData->fCFUStringIndex);
}
if (fRawData->fCFUStringTable != 0) {
fCFUStrings = reinterpret_cast<char16_t*>(reinterpret_cast<char*>(fRawData) + fRawData->fCFUStringTable);
}
}
SpoofData::~SpoofData() {
if (fDataOwned) {
uprv_free(fRawData);
}
fRawData = nullptr;
if (fUDM != nullptr) {
udata_close(fUDM);
}
fUDM = nullptr;
}
void SpoofData::removeReference() {
if (umtx_atomic_dec(&fRefCount) == 0) {
delete this;
}
}
SpoofData *SpoofData::addReference() {
umtx_atomic_inc(&fRefCount);
return this;
}
void *SpoofData::reserveSpace(int32_t numBytes, UErrorCode &status) {
if (U_FAILURE(status)) {
return nullptr;
}
if (!fDataOwned) {
UPRV_UNREACHABLE_EXIT;
}
numBytes = (numBytes + 15) & ~15; // Round up to a multiple of 16
uint32_t returnOffset = fMemLimit;
fMemLimit += numBytes;
fRawData = static_cast<SpoofDataHeader *>(uprv_realloc(fRawData, fMemLimit));
fRawData->fLength = fMemLimit;
uprv_memset((char *)fRawData + returnOffset, 0, numBytes);
initPtrs(status);
return reinterpret_cast<char*>(fRawData) + returnOffset;
}
int32_t SpoofData::serialize(void *buf, int32_t capacity, UErrorCode &status) const {
int32_t dataSize = fRawData->fLength;
if (capacity < dataSize) {
status = U_BUFFER_OVERFLOW_ERROR;
return dataSize;
}
uprv_memcpy(buf, fRawData, dataSize);
return dataSize;
}
int32_t SpoofData::size() const {
return fRawData->fLength;
}
//-------------------------------
//
// Front-end APIs for SpoofData
//
//-------------------------------
int32_t SpoofData::confusableLookup(UChar32 inChar, UnicodeString &dest) const {
// Perform a binary search.
// [lo, hi), i.e lo is inclusive, hi is exclusive.
// The result after the loop will be in lo.
int32_t lo = 0;
int32_t hi = length();
do {
int32_t mid = (lo + hi) / 2;
if (codePointAt(mid) > inChar) {
hi = mid;
} else if (codePointAt(mid) < inChar) {
lo = mid;
} else {
// Found result. Break early.
lo = mid;
break;
}
} while (hi - lo > 1);
// Did we find an entry? If not, the char maps to itself.
if (codePointAt(lo) != inChar) {
dest.append(inChar);
return 1;
}
// Add the element to the string builder and return.
return appendValueTo(lo, dest);
}
int32_t SpoofData::length() const {
return fRawData->fCFUKeysSize;
}
UChar32 SpoofData::codePointAt(int32_t index) const {
return ConfusableDataUtils::keyToCodePoint(fCFUKeys[index]);
}
int32_t SpoofData::appendValueTo(int32_t index, UnicodeString& dest) const {
int32_t stringLength = ConfusableDataUtils::keyToLength(fCFUKeys[index]);
// Value is either a char (for strings of length 1) or
// an index into the string table (for longer strings)
uint16_t value = fCFUValues[index];
if (stringLength == 1) {
dest.append(static_cast<char16_t>(value));
} else {
dest.append(fCFUStrings + value, stringLength);
}
return stringLength;
}
U_NAMESPACE_END
U_NAMESPACE_USE
//-----------------------------------------------------------------------------
//
// uspoof_swap - byte swap and char encoding swap of spoof data
//
//-----------------------------------------------------------------------------
U_CAPI int32_t U_EXPORT2
uspoof_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,
UErrorCode *status) {
if (status == nullptr || U_FAILURE(*status)) {
return 0;
}
if(ds==nullptr || inData==nullptr || length<-1 || (length>0 && outData==nullptr)) {
*status=U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
//
// Check that the data header is for spoof data.
// (Header contents are defined in gencfu.cpp)
//
const UDataInfo *pInfo = (const UDataInfo *)((const char *)inData+4);
if(!( pInfo->dataFormat[0]==0x43 && /* dataFormat="Cfu " */
pInfo->dataFormat[1]==0x66 &&
pInfo->dataFormat[2]==0x75 &&
pInfo->dataFormat[3]==0x20 &&
pInfo->formatVersion[0]==USPOOF_CONFUSABLE_DATA_FORMAT_VERSION &&
pInfo->formatVersion[1]==0 &&
pInfo->formatVersion[2]==0 &&
pInfo->formatVersion[3]==0 )) {
udata_printError(ds, "uspoof_swap(): data format %02x.%02x.%02x.%02x "
"(format version %02x %02x %02x %02x) is not recognized\n",
pInfo->dataFormat[0], pInfo->dataFormat[1],
pInfo->dataFormat[2], pInfo->dataFormat[3],
pInfo->formatVersion[0], pInfo->formatVersion[1],
pInfo->formatVersion[2], pInfo->formatVersion[3]);
*status=U_UNSUPPORTED_ERROR;
return 0;
}
//
// Swap the data header. (This is the generic ICU Data Header, not the uspoof Specific
// header). This swap also conveniently gets us
// the size of the ICU d.h., which lets us locate the start
// of the uspoof specific data.
//
int32_t headerSize=udata_swapDataHeader(ds, inData, length, outData, status);
//
// Get the Spoof Data Header, and check that it appears to be OK.
//
//
const uint8_t *inBytes =(const uint8_t *)inData+headerSize;
SpoofDataHeader *spoofDH = (SpoofDataHeader *)inBytes;
if (ds->readUInt32(spoofDH->fMagic) != USPOOF_MAGIC ||
ds->readUInt32(spoofDH->fLength) < sizeof(SpoofDataHeader))
{
udata_printError(ds, "uspoof_swap(): Spoof Data header is invalid.\n");
*status=U_UNSUPPORTED_ERROR;
return 0;
}
//
// Prefight operation? Just return the size
//
int32_t spoofDataLength = ds->readUInt32(spoofDH->fLength);
int32_t totalSize = headerSize + spoofDataLength;
if (length < 0) {
return totalSize;
}
//
// Check that length passed in is consistent with length from Spoof data header.
//
if (length < totalSize) {
udata_printError(ds, "uspoof_swap(): too few bytes (%d after ICU Data header) for spoof data.\n",
spoofDataLength);
*status=U_INDEX_OUTOFBOUNDS_ERROR;
return 0;
}
//
// Swap the Data. Do the data itself first, then the Spoof Data Header, because
// we need to reference the header to locate the data, and an
// inplace swap of the header leaves it unusable.
//
uint8_t *outBytes = (uint8_t *)outData + headerSize;
SpoofDataHeader *outputDH = (SpoofDataHeader *)outBytes;
int32_t sectionStart;
int32_t sectionLength;
//
// If not swapping in place, zero out the output buffer before starting.
// Gaps may exist between the individual sections, and these must be zeroed in
// the output buffer. The simplest way to do that is to just zero the whole thing.
//
if (inBytes != outBytes) {
uprv_memset(outBytes, 0, spoofDataLength);
}
// Confusables Keys Section (fCFUKeys)
sectionStart = ds->readUInt32(spoofDH->fCFUKeys);
sectionLength = ds->readUInt32(spoofDH->fCFUKeysSize) * 4;
ds->swapArray32(ds, inBytes+sectionStart, sectionLength, outBytes+sectionStart, status);
// String Index Section
sectionStart = ds->readUInt32(spoofDH->fCFUStringIndex);
sectionLength = ds->readUInt32(spoofDH->fCFUStringIndexSize) * 2;
ds->swapArray16(ds, inBytes+sectionStart, sectionLength, outBytes+sectionStart, status);
// String Table Section
sectionStart = ds->readUInt32(spoofDH->fCFUStringTable);
sectionLength = ds->readUInt32(spoofDH->fCFUStringTableLen) * 2;
ds->swapArray16(ds, inBytes+sectionStart, sectionLength, outBytes+sectionStart, status);
// And, last, swap the header itself.
// int32_t fMagic // swap this
// uint8_t fFormatVersion[4] // Do not swap this, just copy
// int32_t fLength and all the rest // Swap the rest, all is 32 bit stuff.
//
uint32_t magic = ds->readUInt32(spoofDH->fMagic);
ds->writeUInt32((uint32_t *)&outputDH->fMagic, magic);
if (inBytes != outBytes) {
uprv_memcpy(outputDH->fFormatVersion, spoofDH->fFormatVersion, sizeof(spoofDH->fFormatVersion));
}
// swap starting at fLength
ds->swapArray32(ds, &spoofDH->fLength, sizeof(SpoofDataHeader)-8 /* minus magic and fFormatVersion[4] */, &outputDH->fLength, status);
return totalSize;
}
#endif

344
thirdparty/icu4c/i18n/uspoof_impl.h vendored Normal file
View File

@@ -0,0 +1,344 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
***************************************************************************
* Copyright (C) 2008-2013, International Business Machines Corporation
* and others. All Rights Reserved.
***************************************************************************
*
* uspoof_impl.h
*
* Implementation header for spoof detection
*
*/
#ifndef USPOOFIM_H
#define USPOOFIM_H
#include "uassert.h"
#include "unicode/utypes.h"
#include "unicode/uspoof.h"
#include "unicode/uscript.h"
#include "unicode/udata.h"
#include "udataswp.h"
#include "utrie2.h"
#if !UCONFIG_NO_NORMALIZATION
#ifdef __cplusplus
#include "capi_helper.h"
#include "umutex.h"
U_NAMESPACE_BEGIN
// The maximum length (in UTF-16 UChars) of the skeleton replacement string resulting from
// a single input code point. This is function of the unicode.org data.
#define USPOOF_MAX_SKELETON_EXPANSION 20
// The default stack buffer size for copies or conversions or normalizations
// of input strings being checked. (Used in multiple places.)
#define USPOOF_STACK_BUFFER_SIZE 100
// Magic number for sanity checking spoof data.
#define USPOOF_MAGIC 0x3845fdef
// Magic number for sanity checking spoof checkers.
#define USPOOF_CHECK_MAGIC 0x2734ecde
class ScriptSet;
class SpoofData;
struct SpoofDataHeader;
class ConfusableDataUtils;
/**
* Class SpoofImpl corresponds directly to the plain C API opaque type
* USpoofChecker. One can be cast to the other.
*/
class SpoofImpl : public UObject,
public IcuCApiHelper<USpoofChecker, SpoofImpl, USPOOF_MAGIC> {
public:
SpoofImpl(SpoofData *data, UErrorCode& status);
SpoofImpl(UErrorCode& status);
SpoofImpl();
void construct(UErrorCode& status);
virtual ~SpoofImpl();
/** Copy constructor, used by the user level uspoof_clone() function.
*/
SpoofImpl(const SpoofImpl &src, UErrorCode &status);
USpoofChecker *asUSpoofChecker();
static SpoofImpl *validateThis(USpoofChecker *sc, UErrorCode &status);
static const SpoofImpl *validateThis(const USpoofChecker *sc, UErrorCode &status);
/** Set and Get AllowedLocales, implementations of the corresponding API */
void setAllowedLocales(const char *localesList, UErrorCode &status);
const char * getAllowedLocales(UErrorCode &status);
// Add (union) to the UnicodeSet all of the characters for the scripts used for
// the specified locale. Part of the implementation of setAllowedLocales.
void addScriptChars(const char *locale, UnicodeSet *allowedChars, UErrorCode &status);
// Functions implementing the features of UTS 39 section 5.
static void getAugmentedScriptSet(UChar32 codePoint, ScriptSet& result, UErrorCode& status);
void getResolvedScriptSet(const UnicodeString& input, ScriptSet& result, UErrorCode& status) const;
void getResolvedScriptSetWithout(const UnicodeString& input, UScriptCode script, ScriptSet& result, UErrorCode& status) const;
void getNumerics(const UnicodeString& input, UnicodeSet& result, UErrorCode& status) const;
URestrictionLevel getRestrictionLevel(const UnicodeString& input, UErrorCode& status) const;
int32_t findHiddenOverlay(const UnicodeString& input, UErrorCode& status) const;
bool isIllegalCombiningDotLeadCharacter(UChar32 cp) const;
/** parse a hex number. Untility used by the builders. */
static UChar32 ScanHex(const char16_t *s, int32_t start, int32_t limit, UErrorCode &status);
static UClassID U_EXPORT2 getStaticClassID();
virtual UClassID getDynamicClassID() const override;
//
// Data Members
//
int32_t fChecks; // Bit vector of checks to perform.
SpoofData *fSpoofData;
const UnicodeSet *fAllowedCharsSet; // The UnicodeSet of allowed characters.
// for this Spoof Checker. Defaults to all chars.
const char *fAllowedLocales; // The list of allowed locales.
URestrictionLevel fRestrictionLevel; // The maximum restriction level for an acceptable identifier.
};
/**
* Class CheckResult corresponds directly to the plain C API opaque type
* USpoofCheckResult. One can be cast to the other.
*/
class CheckResult : public UObject,
public IcuCApiHelper<USpoofCheckResult, CheckResult, USPOOF_CHECK_MAGIC> {
public:
CheckResult();
virtual ~CheckResult();
USpoofCheckResult *asUSpoofCheckResult();
static CheckResult *validateThis(USpoofCheckResult *ptr, UErrorCode &status);
static const CheckResult *validateThis(const USpoofCheckResult *ptr, UErrorCode &status);
void clear();
// Used to convert this CheckResult to the older int32_t return value API
int32_t toCombinedBitmask(int32_t expectedChecks);
// Data Members
int32_t fChecks; // Bit vector of checks that were failed.
UnicodeSet fNumerics; // Set of numerics found in the string.
URestrictionLevel fRestrictionLevel; // The restriction level of the string.
};
//
// Confusable Mappings Data Structures, version 2.0
//
// For the confusable data, we are essentially implementing a map,
// key: a code point
// value: a string. Most commonly one char in length, but can be more.
//
// The keys are stored as a sorted array of 32 bit ints.
// bits 0-23 a code point value
// bits 24-31 length of value string, in UChars (between 1 and 256 UChars).
// The key table is sorted in ascending code point order. (not on the
// 32 bit int value, the flag bits do not participate in the sorting.)
//
// Lookup is done by means of a binary search in the key table.
//
// The corresponding values are kept in a parallel array of 16 bit ints.
// If the value string is of length 1, it is literally in the value array.
// For longer strings, the value array contains an index into the strings table.
//
// String Table:
// The strings table contains all of the value strings (those of length two or greater)
// concatenated together into one long char16_t (UTF-16) array.
//
// There is no nul character or other mark between adjacent strings.
//
//----------------------------------------------------------------------------
//
// Changes from format version 1 to format version 2:
// 1) Removal of the whole-script confusable data tables.
// 2) Removal of the SL/SA/ML/MA and multi-table flags in the key bitmask.
// 3) Expansion of string length value in the key bitmask from 2 bits to 8 bits.
// 4) Removal of the string lengths table since 8 bits is sufficient for the
// lengths of all entries in confusables.txt.
// Internal functions for manipulating confusable data table keys
#define USPOOF_CONFUSABLE_DATA_FORMAT_VERSION 2 // version for ICU 58
class ConfusableDataUtils {
public:
inline static UChar32 keyToCodePoint(int32_t key) {
return key & 0x00ffffff;
}
inline static int32_t keyToLength(int32_t key) {
return ((key & 0xff000000) >> 24) + 1;
}
inline static int32_t codePointAndLengthToKey(UChar32 codePoint, int32_t length) {
U_ASSERT((codePoint & 0x00ffffff) == codePoint);
U_ASSERT(length <= 256);
return codePoint | ((length - 1) << 24);
}
};
//-------------------------------------------------------------------------------------
//
// SpoofData
//
// A small class that wraps the raw (usually memory mapped) spoof data.
// Serves two primary functions:
// 1. Convenience. Contains real pointers to the data, to avoid dealing with
// the offsets in the raw data.
// 2. Reference counting. When a spoof checker is cloned, the raw data is shared
// and must be retained until all checkers using the data are closed.
// Nothing in this struct includes state that is specific to any particular
// USpoofDetector object.
//
//---------------------------------------------------------------------------------------
class SpoofData: public UMemory {
public:
static SpoofData* getDefault(UErrorCode &status); // Get standard ICU spoof data.
static void releaseDefault(); // Cleanup reference to default spoof data.
SpoofData(UErrorCode &status); // Create new spoof data wrapper.
// Only used when building new data from rules.
// Constructor for use when creating from prebuilt default data.
// A UDataMemory is what the ICU internal data loading functions provide.
// The udm is adopted by the SpoofData.
SpoofData(UDataMemory *udm, UErrorCode &status);
// Constructor for use when creating from serialized data.
//
SpoofData(const void *serializedData, int32_t length, UErrorCode &status);
// Check raw Spoof Data Version compatibility.
// Return true it looks good.
UBool validateDataVersion(UErrorCode &status) const;
~SpoofData(); // Destructor not normally used.
// Use removeReference() instead.
// Reference Counting functions.
// Clone of a user-level spoof detector increments the ref count on the data.
// Close of a user-level spoof detector decrements the ref count.
// If the data is owned by us, it will be deleted when count goes to zero.
SpoofData *addReference();
void removeReference();
// Reset all fields to an initial state.
// Called from the top of all constructors.
void reset();
// Copy this instance's raw data buffer to the specified address.
int32_t serialize(void *buf, int32_t capacity, UErrorCode &status) const;
// Get the total number of bytes of data backed by this SpoofData.
// Not to be confused with length, which returns the number of confusable entries.
int32_t size() const;
// Get the confusable skeleton transform for a single code point.
// The result is a string with a length between 1 and 18 as of Unicode 9.
// This is the main public endpoint for this class.
// @return The length in UTF-16 code units of the substitution string.
int32_t confusableLookup(UChar32 inChar, UnicodeString &dest) const;
// Get the number of confusable entries in this SpoofData.
int32_t length() const;
// Get the code point (key) at the specified index.
UChar32 codePointAt(int32_t index) const;
// Get the confusable skeleton (value) at the specified index.
// Append it to the specified UnicodeString&.
// @return The length in UTF-16 code units of the skeleton string.
int32_t appendValueTo(int32_t index, UnicodeString& dest) const;
private:
// Reserve space in the raw data. For use by builder when putting together a
// new set of data. Init the new storage to zero, to prevent inconsistent
// results if it is not all otherwise set by the requester.
// Return:
// pointer to the new space that was added by this function.
void *reserveSpace(int32_t numBytes, UErrorCode &status);
// initialize the pointers from this object to the raw data.
void initPtrs(UErrorCode &status);
SpoofDataHeader *fRawData; // Ptr to the raw memory-mapped data
UBool fDataOwned; // True if the raw data is owned, and needs
// to be deleted when refcount goes to zero.
UDataMemory *fUDM; // If not nullptr, our data came from a
// UDataMemory, which we must close when
// we are done.
uint32_t fMemLimit; // Limit of available raw data space
u_atomic_int32_t fRefCount;
// Confusable data
int32_t *fCFUKeys;
uint16_t *fCFUValues;
char16_t *fCFUStrings;
friend class ConfusabledataBuilder;
};
//---------------------------------------------------------------------------------------
//
// Raw Binary Data Formats, as loaded from the ICU data file,
// or as built by the builder.
//
//---------------------------------------------------------------------------------------
struct SpoofDataHeader {
int32_t fMagic; // (0x3845fdef)
uint8_t fFormatVersion[4]; // Data Format. Same as the value in struct UDataInfo
// if there is one associated with this data.
int32_t fLength; // Total length in bytes of this spoof data,
// including all sections, not just the header.
// The following four sections refer to data representing the confusable data
// from the Unicode.org data from "confusables.txt"
int32_t fCFUKeys; // byte offset to Keys table (from SpoofDataHeader *)
int32_t fCFUKeysSize; // number of entries in keys table (32 bits each)
// TODO: change name to fCFUValues, for consistency.
int32_t fCFUStringIndex; // byte offset to String Indexes table
int32_t fCFUStringIndexSize; // number of entries in String Indexes table (16 bits each)
// (number of entries must be same as in Keys table
int32_t fCFUStringTable; // byte offset of String table
int32_t fCFUStringTableLen; // length of string table (in 16 bit UChars)
// The following sections are for data from xidmodifications.txt
int32_t unused[15]; // Padding, Room for Expansion
};
U_NAMESPACE_END
#endif /* __cplusplus */
/**
* Endianness swap function for binary spoof data.
* @internal
*/
U_CAPI int32_t U_EXPORT2
uspoof_swap(const UDataSwapper *ds, const void *inData, int32_t length, void *outData,
UErrorCode *status);
#endif
#endif /* USPOOFIM_H */