android jni检测 char utf8

JNI WARNING: input is not valid Modified UTF-8: illegal start byte

在加解密可能会出现非utf8字符
导致vm挂掉,所以需要在 NewStringUTF之前验证char*是不是含有非utf8字符
从vm扣除可用源码
typedef uint8_t         jboolean;       /* unsigned 8 bits */
类型
typedef u1 uint8_t;         

[cpp]  view plain copy
  1. static u1 checkUtfBytes(const char* bytes, const char** errorKind) {  
  2.      while (*bytes != '\0') {  
  3.          u1 utf8 = *(bytes++);  
  4.          // Switch on the high four bits.  
  5.          switch (utf8 >> 4) {  
  6.          case 0x00:  
  7.          case 0x01:  
  8.          case 0x02:  
  9.          case 0x03:  
  10.          case 0x04:  
  11.          case 0x05:  
  12.          case 0x06:  
  13.          case 0x07:  
  14.              // Bit pattern 0xxx. No need for any extra bytes.  
  15.              break;  
  16.          case 0x08:  
  17.          case 0x09:  
  18.          case 0x0a:  
  19.          case 0x0b:  
  20.          case 0x0f:  
  21.              /* 
  22.               * Bit pattern 10xx or 1111, which are illegal start bytes. 
  23.               * Note: 1111 is valid for normal UTF-8, but not the 
  24.               * modified UTF-8 used here. 
  25.               */  
  26.              *errorKind = "start";  
  27.              return utf8;  
  28.          case 0x0e:  
  29.              // Bit pattern 1110, so there are two additional bytes.  
  30.              utf8 = *(bytes++);  
  31.              if ((utf8 & 0xc0) != 0x80) {  
  32.                  *errorKind = "continuation";  
  33.                  return utf8;  
  34.              }  
  35.              // Fall through to take care of the final byte.  
  36.          case 0x0c:  
  37.          case 0x0d:  
  38.              // Bit pattern 110x, so there is one additional byte.  
  39.              utf8 = *(bytes++);  
  40.              if ((utf8 & 0xc0) != 0x80) {  
  41.                  *errorKind = "continuation";  
  42.                  return utf8;  
  43.              }  
  44.              break;  
  45.          }  
  46.      }  
  47.      return 0;  
  48.  }  
验证函数是上面的
[cpp]  view plain copy
  1. const char* errorKind = NULL;  
  2.     u1 utf8 = checkUtfBytes(bytes, &errorKind);  
  3.     if (errorKind != NULL) {  
  4.         ALOGW("JNI WARNING: input is not valid Modified UTF-8: illegal %s byte %#x", errorKind, utf8);  
  5.         ALOGW("             string: '%s'", bytes);  
  6.         showLocation();  
  7.         abortMaybe();  
  8.     }  

使用:把char和 errorKind传入
如果errorKind不为NULL说明含有非utf-8代码。做相应处理
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值