-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathQMUIStringPrivate.m
412 lines (360 loc) · 23 KB
/
QMUIStringPrivate.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/**
* Tencent is pleased to support the open source community by making QMUI_iOS available.
* Copyright (C) 2016-2021 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
//
// QMUIStringPrivate.m
// QMUIKit
//
// Created by molice on 2021/11/5.
//
#import "QMUIStringPrivate.h"
#import <CommonCrypto/CommonDigest.h>
#import "QMUICore.h"
#import "NSString+QMUI.h"
@implementation QMUIStringPrivate
+ (NSUInteger)transformIndexToDefaultMode:(NSUInteger)index inString:(NSString *)string {
CGFloat strlength = 0.f;
NSUInteger i = 0;
for (i = 0; i < string.length; i++) {
unichar character = [string characterAtIndex:i];
if (isascii(character)) {
strlength += 1;
} else {
strlength += 2;
}
if (strlength >= index + 1) return i;
}
return 0;
}
+ (NSRange)transformRangeToDefaultMode:(NSRange)range lessValue:(BOOL)lessValue inString:(NSString *)string {
CGFloat strlength = 0.f;
NSRange resultRange = NSMakeRange(NSNotFound, 0);
NSUInteger i = 0;
for (i = 0; i < string.length; i++) {
unichar character = [string characterAtIndex:i];
if (isascii(character)) {
strlength += 1;
} else {
strlength += 2;
}
if ((lessValue && isascii(character) && strlength >= range.location + 1)
|| (lessValue && !isascii(character) && strlength > range.location + 1)
|| (!lessValue && strlength >= range.location + 1)) {
if (resultRange.location == NSNotFound) {
resultRange.location = i;
}
if (range.length > 0 && strlength >= NSMaxRange(range)) {
resultRange.length = i - resultRange.location;
if (lessValue && (strlength == NSMaxRange(range))) {
resultRange.length += 1;// 尽量不包含字符的,只有在精准等于时才+1,否则就不算这最后一个字符
} else if (!lessValue) {
resultRange.length += 1;// 只要是最大能力包含字符的,一进来就+1
}
return resultRange;
}
}
}
return resultRange;
}
+ (NSRange)downRoundRangeOfComposedCharacterSequences:(NSRange)range inString:(NSString *)string {
if (range.length == 0) {
return range;
}
NSRange systemRange = [string rangeOfComposedCharacterSequencesForRange:range];// 系统总是往大取值
if (NSEqualRanges(range, systemRange)) {
return range;
}
NSRange result = systemRange;
if (range.location > systemRange.location) {
// 意味着传进来的 range 起点刚好在某个 Character Sequence 中间,所以要把这个 Character Sequence 遗弃掉,从它后面的字符开始算
NSRange beginRange = [string rangeOfComposedCharacterSequenceAtIndex:range.location];
result.location = NSMaxRange(beginRange);
result.length -= beginRange.length;
}
if (NSMaxRange(range) < NSMaxRange(systemRange)) {
// 意味着传进来的 range 终点刚好在某个 Character Sequence 中间,所以要把这个 Character Sequence 遗弃掉,只取到它前面的字符
NSRange endRange = [string rangeOfComposedCharacterSequenceAtIndex:NSMaxRange(range) - 1];
// 如果参数传进来的 range 刚好落在一个 emoji 的中间,就会导致前面减完 beginRange 这里又减掉一个 endRange,出现负数(注意这里 length 是 NSUInteger),所以做个保护,可以用 👨👩👧👦 测试,这个 emoji 长度是 11
if (result.length >= endRange.length) {
result.length = result.length - endRange.length;
} else {
result.length = 0;
}
}
return result;
}
+ (id)substring:(id)aString avoidBreakingUpCharacterSequencesFromIndex:(NSUInteger)index lessValue:(BOOL)lessValue countingNonASCIICharacterAsTwo:(BOOL)countingNonASCIICharacterAsTwo {
NSAttributedString *attributedString = [aString isKindOfClass:NSAttributedString.class] ? (NSAttributedString *)aString : nil;
NSString *string = attributedString.string ?: (NSString *)aString;
NSUInteger length = countingNonASCIICharacterAsTwo ? string.qmui_lengthWhenCountingNonASCIICharacterAsTwo : string.length;
QMUIAssert(index <= length, @"QMUIStringPrivate", @"%s, index %@ out of bounds. string = %@", __func__, @(index), attributedString ?: string);
if (index >= length) {
if (attributedString) {
return [[attributedString.class alloc] init];
}
return @"";
};
index = countingNonASCIICharacterAsTwo ? [self transformIndexToDefaultMode:index inString:string] : index;// 实际计算都按照系统默认的 length 规则来
NSRange range = [string rangeOfComposedCharacterSequenceAtIndex:index];
index = range.length == 1 ? index : (lessValue ? NSMaxRange(range) : range.location);
if (attributedString) {
NSAttributedString *resultString = [attributedString attributedSubstringFromRange:NSMakeRange(index, string.length - index)];
return resultString;
}
NSString *resultString = [string substringFromIndex:index];
return resultString;
}
+ (id)substring:(id)aString avoidBreakingUpCharacterSequencesToIndex:(NSUInteger)index lessValue:(BOOL)lessValue countingNonASCIICharacterAsTwo:(BOOL)countingNonASCIICharacterAsTwo {
NSAttributedString *attributedString = [aString isKindOfClass:NSAttributedString.class] ? (NSAttributedString *)aString : nil;
NSString *string = attributedString.string ?: (NSString *)aString;
NSUInteger length = countingNonASCIICharacterAsTwo ? string.qmui_lengthWhenCountingNonASCIICharacterAsTwo : string.length;
QMUIAssert(index <= length, @"QMUIStringPrivate", @"%s, index %@ out of bounds. string = %@", __func__, @(index), attributedString ?: string);
if (index == 0 || index > length) {
if (attributedString) {
return [[attributedString.class alloc] init];
}
return @"";
}
if (index == length) {// 根据系统 -[NSString substringToIndex:] 的注释,在 index 等于 length 时会返回 self 的 copy。
if (attributedString) {
if ([attributedString isKindOfClass:NSMutableAttributedString.class]) {
return [aString mutableCopy];
}
}
return [aString copy];
}
index = countingNonASCIICharacterAsTwo ? [self transformIndexToDefaultMode:index inString:string] : index;// 实际计算都按照系统默认的 length 规则来
NSRange range = [string rangeOfComposedCharacterSequenceAtIndex:index];
index = range.length == 1 ? index : (lessValue ? range.location : NSMaxRange(range));
if (attributedString) {
NSAttributedString *resultString = [attributedString attributedSubstringFromRange:NSMakeRange(0, index)];
return resultString;
}
NSString *resultString = [string substringToIndex:index];
return resultString;
}
+ (id)substring:(id)aString avoidBreakingUpCharacterSequencesWithRange:(NSRange)range lessValue:(BOOL)lessValue countingNonASCIICharacterAsTwo:(BOOL)countingNonASCIICharacterAsTwo {
NSAttributedString *attributedString = [aString isKindOfClass:NSAttributedString.class] ? (NSAttributedString *)aString : nil;
NSString *string = attributedString.string ?: (NSString *)aString;
NSUInteger length = countingNonASCIICharacterAsTwo ? string.qmui_lengthWhenCountingNonASCIICharacterAsTwo : string.length;
QMUIAssert(NSMaxRange(range) <= length, @"QMUIStringPrivate", @"%s, range %@ out of bounds. string = %@", __func__, NSStringFromRange(range), attributedString ?: string);
if (NSMaxRange(range) > length) {
if (attributedString) {
return [[attributedString.class alloc] init];
}
return @"";
}
range = countingNonASCIICharacterAsTwo ? [self transformRangeToDefaultMode:range lessValue:lessValue inString:string] : range;// 实际计算都按照系统默认的 length 规则来
NSRange characterSequencesRange = lessValue ? [self downRoundRangeOfComposedCharacterSequences:range inString:string] : [string rangeOfComposedCharacterSequencesForRange:range];
if (attributedString) {
NSAttributedString *resultString = [attributedString attributedSubstringFromRange:characterSequencesRange];
return resultString;
}
NSString *resultString = [string substringWithRange:characterSequencesRange];
return resultString;
}
+ (id)string:(id)aString avoidBreakingUpCharacterSequencesByRemoveCharacterAtIndex:(NSUInteger)index {
NSAttributedString *attributedString = [aString isKindOfClass:NSAttributedString.class] ? (NSAttributedString *)aString : nil;
NSString *string = attributedString.string ?: (NSString *)aString;
NSRange rangeForRemove = [string rangeOfComposedCharacterSequenceAtIndex:index];
if (attributedString) {
NSMutableAttributedString *resultString = attributedString.mutableCopy;
[resultString replaceCharactersInRange:rangeForRemove withString:@""];
return resultString.copy;
}
NSString *resultString = [string stringByReplacingCharactersInRange:rangeForRemove withString:@""];
return resultString;
}
@end
@implementation QMUIStringPrivate (Safety)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self qmuisafety_UIKeyboardImpl];
[self qmuisafety_NSRegularExpression];
[self qmuisafety_NSString];
[self qmuisafety_NSAttributedString];
});
}
static BOOL QMUIAvoidSubstring = NO;
+ (void)qmuisafety_UIKeyboardImpl {
// UIKeyboardImpl
// - (void) handleKeyWithString:(id)arg1 forKeyEvent:(id)arg2 executionContext:(id)arg3;
OverrideImplementation(NSClassFromString([NSString qmui_stringByConcat:@"UIKeyb", @"oard", @"Impl", nil]), NSSelectorFromString([NSString qmui_stringByConcat:@"handleKeyWithString:", @"forKeyEvent:", @"executionContext:", nil]), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^(NSObject *selfObject, NSString *string, UIPressesEvent *event, NSObject *context) {
QMUIAvoidSubstring = YES;
// call super
void (*originSelectorIMP)(id, SEL, NSString *, UIPressesEvent *, NSObject *);
originSelectorIMP = (void (*)(id, SEL, id, id, id))originalIMPProvider();
originSelectorIMP(selfObject, originCMD, string, event, context);
QMUIAvoidSubstring = NO;
};
});
}
+ (void)qmuisafety_NSRegularExpression {
// 避免 stringByReplacingMatchesInString 无效
// https://github.com/Tencent/QMUI_iOS/issues/1542
// -[NSRegularExpression(NSReplacement) stringByReplacingMatchesInString:options:range:withTemplate:]
// - (id) stringByReplacingMatchesInString:(id)arg1 options:(unsigned long)arg2 range:(struct _NSRange)arg3 withTemplate:(id)arg4;
OverrideImplementation([NSRegularExpression class], @selector(stringByReplacingMatchesInString:options:range:withTemplate:), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^NSString *(NSRegularExpression *selfObject, NSString *string, NSMatchingOptions options, NSRange range, NSString *templ) {
QMUIAvoidSubstring = YES;
// call super
NSString * (*originSelectorIMP)(id, SEL, NSString *, NSMatchingOptions, NSRange, NSString *);
originSelectorIMP = (NSString * (*)(id, SEL, NSString *, NSMatchingOptions, NSRange, NSString *))originalIMPProvider();
NSString * result = originSelectorIMP(selfObject, originCMD, string, options, range, templ);
QMUIAvoidSubstring = NO;
return result;
};
});
}
+ (void)qmuisafety_NSString {
OverrideImplementation([NSString class], @selector(substringFromIndex:), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^NSString *(NSString *selfObject, NSUInteger index) {
// index 越界
{
BOOL isValidatedIndex = index <= selfObject.length;
if (!isValidatedIndex) {
NSString *logString = [NSString stringWithFormat:@"%@ 传入了一个超过字符串长度的 index: %@,原字符串为: %@(%@)", NSStringFromSelector(originCMD), @(index), selfObject, @(selfObject.length)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
return @"";// 系统 substringFromIndex: 返回值的标志是 nonnull
}
}
// 保护从 emoji 等 ComposedCharacterSequence 中间裁剪的场景
// 系统 emoji 键盘输入过程中一定会调用 substringFromIndex:text.length - 1,导致触发我们这个警告,这里特殊保护一下
{
if (index < selfObject.length && !QMUIAvoidSubstring) {
NSRange range = [selfObject rangeOfComposedCharacterSequenceAtIndex:index];
BOOL isValidatedIndex = range.location == index || NSMaxRange(range) == index;
if (!isValidatedIndex) {
NSString *logString = [NSString stringWithFormat:@"试图在 ComposedCharacterSequence 中间用 %@ 裁剪字符串,可能导致乱码、crash。原字符串为“%@”(%@),index 为 %@,命中的 ComposedCharacterSequence range 为 %@", NSStringFromSelector(originCMD), selfObject, @(selfObject.length), @(index), NSStringFromRange(range)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
index = range.location;
}
}
}
// call super
NSString * (*originSelectorIMP)(id, SEL, NSUInteger);
originSelectorIMP = (NSString * (*)(id, SEL, NSUInteger))originalIMPProvider();
NSString * result = originSelectorIMP(selfObject, originCMD, index);
return result;
};
});
OverrideImplementation([NSString class], @selector(substringToIndex:), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^NSString *(NSString *selfObject, NSUInteger index) {
// index 越界
{
BOOL isValidatedIndex = index <= selfObject.length;
if (!isValidatedIndex) {
NSString *logString = [NSString stringWithFormat:@"%@ 传入了一个超过字符串长度的 index: %@,原字符串为: %@(%@)", NSStringFromSelector(originCMD), @(index), selfObject, @(selfObject.length)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
return @"";// 系统 substringToIndex: 返回值的标志是 nonnull,但返回 nil 比返回 @"" 更安全
}
}
// 保护从 emoji 等 ComposedCharacterSequence 中间裁剪的场景
{
if (index < selfObject.length) {
NSRange range = [selfObject rangeOfComposedCharacterSequenceAtIndex:index];
BOOL isValidatedIndex = range.location == index;
if (!isValidatedIndex) {
NSString *logString = [NSString stringWithFormat:@"试图在 ComposedCharacterSequence 中间用 %@ 裁剪字符串,可能导致乱码、crash。原字符串为“%@”(%@),index 为 %@,命中的 ComposedCharacterSequence range 为 %@", NSStringFromSelector(originCMD), selfObject, @(selfObject.length), @(index), NSStringFromRange(range)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
index = range.location;
}
}
}
// call super
NSString * (*originSelectorIMP)(id, SEL, NSUInteger);
originSelectorIMP = (NSString * (*)(id, SEL, NSUInteger))originalIMPProvider();
NSString * result = originSelectorIMP(selfObject, originCMD, index);
return result;
};
});
// 继承关系是 __NSCFConstantString → __NSCFString → NSMutableString → NSString,其中 __NSCFString 重写了 substringWithRange:(其他 substring 方法没任何人重写),所以这里要 hook __NSCFString 而不是 NSString
OverrideImplementation(NSClassFromString(@"__NSCFString"), @selector(substringWithRange:), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^NSString *(NSString *selfObject, NSRange range) {
// range 越界,注意这里识别不了负值,例如一个 (10, -8) 的 range,它的 NSMaxRange 返回2,会认为长度小于 length 所以合法,但实际上是非法的,所以交给下面的流程专门识别。
{
BOOL isValidddatedRange = NSMaxRange(range) <= selfObject.length;
if (!isValidddatedRange) {
NSString *logString = [NSString stringWithFormat:@"%@ 传入了一个超过字符串长度的 range: %@,原字符串为: %@(%@)", NSStringFromSelector(originCMD), NSStringFromRange(range), selfObject, @(selfObject.length)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
return @"";// 系统 substringWithRange: 返回值的标志是 nonnull
}
}
// rang 负值
{
NSInteger location = range.location;
NSInteger length = range.length;
if (location < 0 || length < 0) {
NSString *logString = [NSString stringWithFormat:@"%@ 传入了一个可能由负数转换过来的 range: %@,猜测转换前数值为 (%@, %@),原字符串为: %@(%@)", NSStringFromSelector(originCMD), NSStringFromRange(range), @(location), @(length), selfObject, @(selfObject.length)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
// return @"";// 由于理论上不可能准确识别这种情况,所以这里不干预 return 值,只是做个 assert 提醒
}
}
// 保护从 emoji 等 ComposedCharacterSequence 中间裁剪的场景
{
if (NSMaxRange(range) < selfObject.length) {
NSRange range2 = [selfObject rangeOfComposedCharacterSequencesForRange:range];
BOOL isValidddatedRange = range.length == 0 || NSEqualRanges(range, range2);
if (!isValidddatedRange && !QMUIAvoidSubstring) {
NSString *logString = [NSString stringWithFormat:@"试图在 ComposedCharacterSequence 中间用 %@ 裁剪字符串,可能导致乱码、crash。原字符串为“%@”(%@),range 为 %@,命中的 ComposedCharacterSequence range 为 %@", NSStringFromSelector(originCMD), selfObject, @(selfObject.length), NSStringFromRange(range), NSStringFromRange(range2)];
QMUIAssert(NO, @"QMUIStringSafety", @"%@", logString);
range = range2;
}
}
}
// call super
NSString * (*originSelectorIMP)(id, SEL, NSRange);
originSelectorIMP = (NSString * (*)(id, SEL, NSRange))originalIMPProvider();
NSString * result = originSelectorIMP(selfObject, originCMD, range);
return result;
};
});
// 保护 -[NSMutableAttributedString appendAttributedString:] 遇到参数为 nil 时会命中系统 assert: nil argument 的场景
// -[__NSCFString replaceCharactersInRange:withString:]
OverrideImplementation(NSClassFromString(@"__NSCFString"), @selector(replaceCharactersInRange:withString:), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^(NSString *selfObject, NSRange firstArgv, id secondArgv) {
if (!secondArgv) {
QMUIAssert(NO, @"QMUIStringPrivate", @"replaceCharactersInRange:withString: 参数 nil 会命中系统 Assert 导致 crash");
secondArgv = @"";
}
// call super
void (*originSelectorIMP)(id, SEL, NSRange, id);
originSelectorIMP = (void (*)(id, SEL, NSRange, id))originalIMPProvider();
originSelectorIMP(selfObject, originCMD, firstArgv, secondArgv);
};
});
}
+ (void)qmuisafety_NSAttributedString {
id (^initWithStringBlock)(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) = ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^id (id selfObject, NSString *str) {
str = str ?: @"";
// call super
id(*originSelectorIMP)(id, SEL, NSString *);
originSelectorIMP = (id (*)(id, SEL, NSString *))originalIMPProvider();
id result = originSelectorIMP(selfObject, originCMD, str);
return result;
};
};
id (^initWithStringAttributesBlock)(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) = ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) {
return ^id (id selfObject, NSString *str, NSDictionary<NSString *, id> *attrs) {
str = str ?: @"";
// call super
id(*originSelectorIMP)(id, SEL, NSString *, NSDictionary<NSString *, id> *);
originSelectorIMP = (id (*)(id, SEL, NSString *, NSDictionary<NSString *, id> *))originalIMPProvider();
id result = originSelectorIMP(selfObject, originCMD, str, attrs);
return result;
};
};
// 类簇对不同的 init 方法对应不同的私有 class,所以要用实例来得到真正的class
OverrideImplementation([[[NSAttributedString alloc] initWithString:@""] class], @selector(initWithString:), initWithStringBlock);
OverrideImplementation([[[NSMutableAttributedString alloc] initWithString:@""] class], @selector(initWithString:), initWithStringBlock);
OverrideImplementation([[[NSAttributedString alloc] initWithString:@"" attributes:nil] class], @selector(initWithString:attributes:), initWithStringAttributesBlock);
OverrideImplementation([[[NSMutableAttributedString alloc] initWithString:@"" attributes:nil] class], @selector(initWithString:attributes:), initWithStringAttributesBlock);
}
@end