1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "Pattern"
18 
19 #include <stdlib.h>
20 
21 #include <nativehelper/JNIHelp.h>
22 #include <nativehelper/jni_macros.h>
23 
24 #include "unicode/parseerr.h"
25 #include "unicode/regex.h"
26 
27 #include "JniConstants.h"
28 #include "ScopedJavaUnicodeString.h"
29 
30 // ICU documentation: http://icu-project.org/apiref/icu4c/classRegexPattern.html
31 
regexDetailMessage(UErrorCode status)32 static const char* regexDetailMessage(UErrorCode status) {
33     // These human-readable error messages were culled from "utypes.h", and then slightly tuned
34     // to make more sense in context.
35     // If we don't have a special-case, we'll just return the textual name of
36     // the enum value (such as U_REGEX_RULE_SYNTAX), which is better than nothing.
37     switch (status) {
38     case U_REGEX_INTERNAL_ERROR: return "An internal error was detected";
39     case U_REGEX_RULE_SYNTAX: return "Syntax error in regexp pattern";
40     case U_REGEX_INVALID_STATE: return "Matcher in invalid state for requested operation";
41     case U_REGEX_BAD_ESCAPE_SEQUENCE: return "Unrecognized backslash escape sequence in pattern";
42     case U_REGEX_PROPERTY_SYNTAX: return "Incorrect Unicode property";
43     case U_REGEX_UNIMPLEMENTED: return "Use of unimplemented feature";
44     case U_REGEX_MISMATCHED_PAREN: return "Incorrectly nested parentheses in regexp pattern";
45     case U_REGEX_NUMBER_TOO_BIG: return "Decimal number is too large";
46     case U_REGEX_BAD_INTERVAL: return "Error in {min,max} interval";
47     case U_REGEX_MAX_LT_MIN: return "In {min,max}, max is less than min";
48     case U_REGEX_INVALID_BACK_REF: return "Back-reference to a non-existent capture group";
49     case U_REGEX_INVALID_FLAG: return "Invalid value for match mode flags";
50     case U_REGEX_LOOK_BEHIND_LIMIT: return "Look-behind pattern matches must have a bounded maximum length";
51     case U_REGEX_SET_CONTAINS_STRING: return "Regular expressions cannot have UnicodeSets containing strings";
52     case U_REGEX_OCTAL_TOO_BIG: return "Octal character constants must be <= 0377.";
53     case U_REGEX_MISSING_CLOSE_BRACKET: return "Missing closing bracket in character class";
54     case U_REGEX_INVALID_RANGE: return "In a character range [x-y], x is greater than y";
55     case U_REGEX_STACK_OVERFLOW: return "Regular expression backtrack stack overflow";
56     case U_REGEX_TIME_OUT: return "Maximum allowed match time exceeded";
57     case U_REGEX_STOPPED_BY_CALLER: return "Matching operation aborted by user callback function";
58     default:
59         return u_errorName(status);
60     }
61 }
62 
throwPatternSyntaxException(JNIEnv * env,UErrorCode status,jstring pattern,UParseError error)63 static void throwPatternSyntaxException(JNIEnv* env, UErrorCode status, jstring pattern, UParseError error) {
64     static jmethodID method = env->GetMethodID(JniConstants::GetPatternSyntaxExceptionClass(env),
65             "<init>", "(Ljava/lang/String;Ljava/lang/String;I)V");
66     jstring message = env->NewStringUTF(regexDetailMessage(status));
67     jclass exceptionClass = JniConstants::GetPatternSyntaxExceptionClass(env);
68     jobject exception = env->NewObject(exceptionClass, method, message, pattern, error.offset);
69     env->Throw(reinterpret_cast<jthrowable>(exception));
70 }
71 
Pattern_free(void * addr)72 static void Pattern_free(void* addr) {
73     delete reinterpret_cast<icu::RegexPattern*>(addr);
74 }
75 
Pattern_getNativeFinalizer(JNIEnv *,jclass)76 static jlong Pattern_getNativeFinalizer(JNIEnv*, jclass) {
77     return reinterpret_cast<jlong>(&Pattern_free);
78 }
79 
Pattern_compileImpl(JNIEnv * env,jclass,jstring javaRegex,jint flags)80 static jlong Pattern_compileImpl(JNIEnv* env, jclass, jstring javaRegex, jint flags) {
81     flags |= UREGEX_ERROR_ON_UNKNOWN_ESCAPES;
82 
83     UErrorCode status = U_ZERO_ERROR;
84     UParseError error;
85     error.offset = -1;
86 
87     ScopedJavaUnicodeString regex(env, javaRegex);
88     if (!regex.valid()) {
89         return 0;
90     }
91     icu::UnicodeString& regexString(regex.unicodeString());
92     icu::RegexPattern* result = icu::RegexPattern::compile(regexString, flags, error, status);
93     if (!U_SUCCESS(status)) {
94         throwPatternSyntaxException(env, status, javaRegex, error);
95     }
96     return static_cast<jlong>(reinterpret_cast<uintptr_t>(result));
97 }
98 
99 static JNINativeMethod gMethods[] = {
100     NATIVE_METHOD(Pattern, compileImpl, "(Ljava/lang/String;I)J"),
101     NATIVE_METHOD(Pattern, getNativeFinalizer, "()J"),
102 };
103 
register_java_util_regex_Pattern(JNIEnv * env)104 void register_java_util_regex_Pattern(JNIEnv* env) {
105     jniRegisterNativeMethods(env, "java/util/regex/Pattern", gMethods, NELEM(gMethods));
106 }
107