python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
#include "clar_libgit2.h" #define URL "https://github.com/libgit2/TestGitRepository" #define REFSPEC "refs/heads/first-merge:refs/remotes/origin/first-merge" static int remote_single_branch(git_remote **out, git_repository *repo, const char *name, const char *url, void *payload) { GIT_UNUSED(payload); cl_git_pass(git_remote_create_with_fetchspec(out, repo, name, url, REFSPEC)); return 0; } void test_online_remotes__single_branch(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; git_repository *repo; git_remote *remote; git_strarray refs; size_t i, count = 0; opts.remote_cb = remote_single_branch; opts.checkout_branch = "first-merge"; cl_git_pass(git_clone(&repo, URL, "./single-branch", &opts)); cl_git_pass(git_reference_list(&refs, repo)); for (i = 0; i < refs.count; i++) { if (!git__prefixcmp(refs.strings[i], "refs/heads/")) count++; } cl_assert_equal_i(1, count); git_strarray_dispose(&refs); cl_git_pass(git_remote_lookup(&remote, repo, "origin")); cl_git_pass(git_remote_get_fetch_refspecs(&refs, remote)); cl_assert_equal_i(1, refs.count); cl_assert_equal_s(REFSPEC, refs.strings[0]); git_strarray_dispose(&refs); git_remote_free(remote); git_repository_free(repo); } void test_online_remotes__restricted_refspecs(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; git_repository *repo; opts.remote_cb = remote_single_branch; cl_git_fail_with(GIT_EINVALIDSPEC, git_clone(&repo, URL, "./restrict-refspec", &opts)); } void test_online_remotes__detached_remote_fails_downloading(void) { git_remote *remote; cl_git_pass(git_remote_create_detached(&remote, URL)); cl_git_pass(git_remote_connect(remote, GIT_DIRECTION_FETCH, NULL, NULL, NULL)); cl_git_fail(git_remote_download(remote, NULL, NULL)); git_remote_free(remote); } void test_online_remotes__detached_remote_fails_uploading(void) { git_remote *remote; cl_git_pass(git_remote_create_detached(&remote, URL)); cl_git_pass(git_remote_connect(remote, GIT_DIRECTION_FETCH, NULL, NULL, NULL)); cl_git_fail(git_remote_upload(remote, NULL, NULL)); git_remote_free(remote); } void test_online_remotes__detached_remote_fails_pushing(void) { git_remote *remote; cl_git_pass(git_remote_create_detached(&remote, URL)); cl_git_pass(git_remote_connect(remote, GIT_DIRECTION_FETCH, NULL, NULL, NULL)); cl_git_fail(git_remote_push(remote, NULL, NULL)); git_remote_free(remote); } void test_online_remotes__detached_remote_succeeds_ls(void) { const char *refs[] = { "HEAD", "refs/heads/first-merge", "refs/heads/master", "refs/heads/no-parent", "refs/tags/annotated_tag", "refs/tags/annotated_tag^{}", "refs/tags/blob", "refs/tags/commit_tree", "refs/tags/nearly-dangling", }; const git_remote_head **heads; git_remote *remote; size_t i, j, n; cl_git_pass(git_remote_create_detached(&remote, URL)); cl_git_pass(git_remote_connect(remote, GIT_DIRECTION_FETCH, NULL, NULL, NULL)); cl_git_pass(git_remote_ls(&heads, &n, remote)); cl_assert_equal_sz(n, 9); for (i = 0; i < n; i++) { char found = false; for (j = 0; j < ARRAY_SIZE(refs); j++) { if (!strcmp(heads[i]->name, refs[j])) { found = true; break; } } cl_assert_(found, heads[i]->name); } git_remote_free(remote); }
libgit2-main
tests/libgit2/online/remotes.c
#include "clar_libgit2.h" #include "git2/clone.h" static git_repository *g_repo; #ifdef GIT_HTTPS static bool g_has_ssl = true; #else static bool g_has_ssl = false; #endif static int cert_check_assert_invalid(git_cert *cert, int valid, const char* host, void *payload) { GIT_UNUSED(cert); GIT_UNUSED(host); GIT_UNUSED(payload); cl_assert_equal_i(0, valid); return GIT_ECERTIFICATE; } void test_online_badssl__expired(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.fetch_opts.callbacks.certificate_check = cert_check_assert_invalid; if (!g_has_ssl) cl_skip(); cl_git_fail_with(GIT_ECERTIFICATE, git_clone(&g_repo, "https://expired.badssl.com/fake.git", "./fake", NULL)); cl_git_fail_with(GIT_ECERTIFICATE, git_clone(&g_repo, "https://expired.badssl.com/fake.git", "./fake", &opts)); } void test_online_badssl__wrong_host(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.fetch_opts.callbacks.certificate_check = cert_check_assert_invalid; if (!g_has_ssl) cl_skip(); cl_git_fail_with(GIT_ECERTIFICATE, git_clone(&g_repo, "https://wrong.host.badssl.com/fake.git", "./fake", NULL)); cl_git_fail_with(GIT_ECERTIFICATE, git_clone(&g_repo, "https://wrong.host.badssl.com/fake.git", "./fake", &opts)); } void test_online_badssl__self_signed(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.fetch_opts.callbacks.certificate_check = cert_check_assert_invalid; if (!g_has_ssl) cl_skip(); cl_git_fail_with(GIT_ECERTIFICATE, git_clone(&g_repo, "https://self-signed.badssl.com/fake.git", "./fake", NULL)); cl_git_fail_with(GIT_ECERTIFICATE, git_clone(&g_repo, "https://self-signed.badssl.com/fake.git", "./fake", &opts)); } void test_online_badssl__old_cipher(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.fetch_opts.callbacks.certificate_check = cert_check_assert_invalid; if (!g_has_ssl) cl_skip(); cl_git_fail(git_clone(&g_repo, "https://rc4.badssl.com/fake.git", "./fake", NULL)); cl_git_fail(git_clone(&g_repo, "https://rc4.badssl.com/fake.git", "./fake", &opts)); }
libgit2-main
tests/libgit2/online/badssl.c
#include "clar_libgit2.h" #include "git2/clone.h" #include "git2/cred_helpers.h" #include "remote.h" #include "futils.h" #include "refs.h" #define LIVE_REPO_URL "http://github.com/libgit2/TestGitRepository" #define LIVE_EMPTYREPO_URL "http://github.com/libgit2/TestEmptyRepository" #define BB_REPO_URL "https://[email protected]/libgit2-test/testgitrepository.git" #define BB_REPO_URL_WITH_PASS "https://libgit2-test:[email protected]/libgit2-test/testgitrepository.git" #define BB_REPO_URL_WITH_WRONG_PASS "https://libgit2-test:[email protected]/libgit2-test/testgitrepository.git" #define GOOGLESOURCE_REPO_URL "https://chromium.googlesource.com/external/github.com/sergi/go-diff" #define SSH_REPO_URL "ssh://github.com/libgit2/TestGitRepository" static git_repository *g_repo; static git_clone_options g_options; static char *_remote_url = NULL; static char *_remote_user = NULL; static char *_remote_pass = NULL; static char *_remote_branch = NULL; static char *_remote_sslnoverify = NULL; static char *_remote_ssh_pubkey = NULL; static char *_remote_ssh_privkey = NULL; static char *_remote_ssh_passphrase = NULL; static char *_remote_ssh_fingerprint = NULL; static char *_remote_proxy_scheme = NULL; static char *_remote_proxy_host = NULL; static char *_remote_proxy_user = NULL; static char *_remote_proxy_pass = NULL; static char *_remote_proxy_selfsigned = NULL; static char *_remote_expectcontinue = NULL; static char *_remote_redirect_initial = NULL; static char *_remote_redirect_subsequent = NULL; static int _orig_proxies_need_reset = 0; static char *_orig_http_proxy = NULL; static char *_orig_https_proxy = NULL; static char *_orig_no_proxy = NULL; static int ssl_cert(git_cert *cert, int valid, const char *host, void *payload) { GIT_UNUSED(cert); GIT_UNUSED(host); GIT_UNUSED(payload); if (_remote_sslnoverify != NULL) valid = 1; return valid ? 0 : GIT_ECERTIFICATE; } void test_online_clone__initialize(void) { git_checkout_options dummy_opts = GIT_CHECKOUT_OPTIONS_INIT; git_fetch_options dummy_fetch = GIT_FETCH_OPTIONS_INIT; g_repo = NULL; memset(&g_options, 0, sizeof(git_clone_options)); g_options.version = GIT_CLONE_OPTIONS_VERSION; g_options.checkout_opts = dummy_opts; g_options.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; g_options.fetch_opts = dummy_fetch; g_options.fetch_opts.callbacks.certificate_check = ssl_cert; _remote_url = cl_getenv("GITTEST_REMOTE_URL"); _remote_user = cl_getenv("GITTEST_REMOTE_USER"); _remote_pass = cl_getenv("GITTEST_REMOTE_PASS"); _remote_branch = cl_getenv("GITTEST_REMOTE_BRANCH"); _remote_sslnoverify = cl_getenv("GITTEST_REMOTE_SSL_NOVERIFY"); _remote_ssh_pubkey = cl_getenv("GITTEST_REMOTE_SSH_PUBKEY"); _remote_ssh_privkey = cl_getenv("GITTEST_REMOTE_SSH_KEY"); _remote_ssh_passphrase = cl_getenv("GITTEST_REMOTE_SSH_PASSPHRASE"); _remote_ssh_fingerprint = cl_getenv("GITTEST_REMOTE_SSH_FINGERPRINT"); _remote_proxy_scheme = cl_getenv("GITTEST_REMOTE_PROXY_SCHEME"); _remote_proxy_host = cl_getenv("GITTEST_REMOTE_PROXY_HOST"); _remote_proxy_user = cl_getenv("GITTEST_REMOTE_PROXY_USER"); _remote_proxy_pass = cl_getenv("GITTEST_REMOTE_PROXY_PASS"); _remote_proxy_selfsigned = cl_getenv("GITTEST_REMOTE_PROXY_SELFSIGNED"); _remote_expectcontinue = cl_getenv("GITTEST_REMOTE_EXPECTCONTINUE"); _remote_redirect_initial = cl_getenv("GITTEST_REMOTE_REDIRECT_INITIAL"); _remote_redirect_subsequent = cl_getenv("GITTEST_REMOTE_REDIRECT_SUBSEQUENT"); if (_remote_expectcontinue) git_libgit2_opts(GIT_OPT_ENABLE_HTTP_EXPECT_CONTINUE, 1); _orig_proxies_need_reset = 0; } void test_online_clone__cleanup(void) { if (g_repo) { git_repository_free(g_repo); g_repo = NULL; } cl_fixture_cleanup("./foo"); cl_fixture_cleanup("./initial"); cl_fixture_cleanup("./subsequent"); git__free(_remote_url); git__free(_remote_user); git__free(_remote_pass); git__free(_remote_branch); git__free(_remote_sslnoverify); git__free(_remote_ssh_pubkey); git__free(_remote_ssh_privkey); git__free(_remote_ssh_passphrase); git__free(_remote_ssh_fingerprint); git__free(_remote_proxy_scheme); git__free(_remote_proxy_host); git__free(_remote_proxy_user); git__free(_remote_proxy_pass); git__free(_remote_proxy_selfsigned); git__free(_remote_expectcontinue); git__free(_remote_redirect_initial); git__free(_remote_redirect_subsequent); if (_orig_proxies_need_reset) { cl_setenv("HTTP_PROXY", _orig_http_proxy); cl_setenv("HTTPS_PROXY", _orig_https_proxy); cl_setenv("NO_PROXY", _orig_no_proxy); git__free(_orig_http_proxy); git__free(_orig_https_proxy); git__free(_orig_no_proxy); } git_libgit2_opts(GIT_OPT_SET_SSL_CERT_LOCATIONS, NULL, NULL); } void test_online_clone__network_full(void) { git_remote *origin; cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); cl_assert(!git_repository_is_bare(g_repo)); cl_git_pass(git_remote_lookup(&origin, g_repo, "origin")); cl_assert_equal_i(GIT_REMOTE_DOWNLOAD_TAGS_AUTO, origin->download_tags); git_remote_free(origin); } void test_online_clone__network_bare(void) { git_remote *origin; g_options.bare = true; cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); cl_assert(git_repository_is_bare(g_repo)); cl_git_pass(git_remote_lookup(&origin, g_repo, "origin")); git_remote_free(origin); } void test_online_clone__empty_repository(void) { git_reference *head; cl_git_pass(git_clone(&g_repo, LIVE_EMPTYREPO_URL, "./foo", &g_options)); cl_assert_equal_i(true, git_repository_is_empty(g_repo)); cl_assert_equal_i(true, git_repository_head_unborn(g_repo)); cl_git_pass(git_reference_lookup(&head, g_repo, GIT_HEAD_FILE)); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head)); cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head)); git_reference_free(head); } static void checkout_progress(const char *path, size_t cur, size_t tot, void *payload) { bool *was_called = (bool*)payload; GIT_UNUSED(path); GIT_UNUSED(cur); GIT_UNUSED(tot); (*was_called) = true; } static int fetch_progress(const git_indexer_progress *stats, void *payload) { bool *was_called = (bool*)payload; GIT_UNUSED(stats); (*was_called) = true; return 0; } void test_online_clone__can_checkout_a_cloned_repo(void) { git_str path = GIT_STR_INIT; git_reference *head, *remote_head; bool checkout_progress_cb_was_called = false, fetch_progress_cb_was_called = false; g_options.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; g_options.checkout_opts.progress_cb = &checkout_progress; g_options.checkout_opts.progress_payload = &checkout_progress_cb_was_called; g_options.fetch_opts.callbacks.transfer_progress = &fetch_progress; g_options.fetch_opts.callbacks.payload = &fetch_progress_cb_was_called; cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); cl_git_pass(git_str_joinpath(&path, git_repository_workdir(g_repo), "master.txt")); cl_assert_equal_i(true, git_fs_path_isfile(git_str_cstr(&path))); cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD")); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head)); cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head)); cl_git_pass(git_reference_lookup(&remote_head, g_repo, "refs/remotes/origin/HEAD")); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(remote_head)); cl_assert_equal_s("refs/remotes/origin/master", git_reference_symbolic_target(remote_head)); cl_assert_equal_i(true, checkout_progress_cb_was_called); cl_assert_equal_i(true, fetch_progress_cb_was_called); git_reference_free(remote_head); git_reference_free(head); git_str_dispose(&path); } static int remote_mirror_cb(git_remote **out, git_repository *repo, const char *name, const char *url, void *payload) { int error; git_remote *remote; GIT_UNUSED(payload); if ((error = git_remote_create_with_fetchspec(&remote, repo, name, url, "+refs/*:refs/*")) < 0) return error; *out = remote; return 0; } void test_online_clone__clone_mirror(void) { git_clone_options opts = GIT_CLONE_OPTIONS_INIT; git_reference *head; bool fetch_progress_cb_was_called = false; opts.fetch_opts.callbacks.transfer_progress = &fetch_progress; opts.fetch_opts.callbacks.payload = &fetch_progress_cb_was_called; opts.bare = true; opts.remote_cb = remote_mirror_cb; cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo.git", &opts)); cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD")); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head)); cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head)); cl_assert_equal_i(true, fetch_progress_cb_was_called); git_reference_free(head); git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup("./foo.git"); } static int update_tips(const char *refname, const git_oid *a, const git_oid *b, void *payload) { int *callcount = (int*)payload; GIT_UNUSED(refname); GIT_UNUSED(a); GIT_UNUSED(b); *callcount = *callcount + 1; return 0; } void test_online_clone__custom_remote_callbacks(void) { int callcount = 0; g_options.fetch_opts.callbacks.update_tips = update_tips; g_options.fetch_opts.callbacks.payload = &callcount; cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); cl_assert(callcount > 0); } void test_online_clone__custom_headers(void) { char *empty_header = ""; char *unnamed_header = "this is a header about nothing"; char *newlines = "X-Custom: almost OK\n"; char *conflict = "Accept: defined-by-git"; char *ok = "X-Custom: this should be ok"; g_options.fetch_opts.custom_headers.count = 1; g_options.fetch_opts.custom_headers.strings = &empty_header; cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); g_options.fetch_opts.custom_headers.strings = &unnamed_header; cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); g_options.fetch_opts.custom_headers.strings = &newlines; cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); g_options.fetch_opts.custom_headers.strings = &conflict; cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); /* Finally, we got it right! */ g_options.fetch_opts.custom_headers.strings = &ok; cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); } static int cred_failure_cb( git_credential **cred, const char *url, const char *username_from_url, unsigned int allowed_types, void *data) { GIT_UNUSED(cred); GIT_UNUSED(url); GIT_UNUSED(username_from_url); GIT_UNUSED(allowed_types); GIT_UNUSED(data); return -172; } void test_online_clone__cred_callback_failure_return_code_is_tunnelled(void) { git__free(_remote_url); git__free(_remote_user); _remote_url = git__strdup("https://github.com/libgit2/non-existent"); _remote_user = git__strdup("libgit2test"); g_options.fetch_opts.callbacks.credentials = cred_failure_cb; cl_git_fail_with(-172, git_clone(&g_repo, _remote_url, "./foo", &g_options)); } static int cred_count_calls_cb(git_credential **cred, const char *url, const char *user, unsigned int allowed_types, void *data) { size_t *counter = (size_t *) data; GIT_UNUSED(url); GIT_UNUSED(user); GIT_UNUSED(allowed_types); if (allowed_types == GIT_CREDENTIAL_USERNAME) return git_credential_username_new(cred, "foo"); (*counter)++; if (*counter == 3) return GIT_EUSER; return git_credential_userpass_plaintext_new(cred, "foo", "bar"); } void test_online_clone__cred_callback_called_again_on_auth_failure(void) { size_t counter = 0; git__free(_remote_url); git__free(_remote_user); _remote_url = git__strdup("https://gitlab.com/libgit2/non-existent"); _remote_user = git__strdup("libgit2test"); g_options.fetch_opts.callbacks.credentials = cred_count_calls_cb; g_options.fetch_opts.callbacks.payload = &counter; cl_git_fail_with(GIT_EUSER, git_clone(&g_repo, _remote_url, "./foo", &g_options)); cl_assert_equal_i(3, counter); } static int cred_default( git_credential **cred, const char *url, const char *user_from_url, unsigned int allowed_types, void *payload) { GIT_UNUSED(url); GIT_UNUSED(user_from_url); GIT_UNUSED(payload); if (!(allowed_types & GIT_CREDENTIAL_DEFAULT)) return 0; return git_credential_default_new(cred); } void test_online_clone__credentials(void) { /* Remote URL environment variable must be set. * User and password are optional. */ git_credential_userpass_payload user_pass = { _remote_user, _remote_pass }; if (!_remote_url) clar__skip(); if (cl_is_env_set("GITTEST_REMOTE_DEFAULT")) { g_options.fetch_opts.callbacks.credentials = cred_default; } else { g_options.fetch_opts.callbacks.credentials = git_credential_userpass; g_options.fetch_opts.callbacks.payload = &user_pass; } cl_git_pass(git_clone(&g_repo, _remote_url, "./foo", &g_options)); git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup("./foo"); } void test_online_clone__credentials_via_custom_headers(void) { const char *creds = "libgit2-test:YT77Ppm2nq8w4TYjGS8U"; git_str auth = GIT_STR_INIT; cl_git_pass(git_str_puts(&auth, "Authorization: Basic ")); cl_git_pass(git_str_encode_base64(&auth, creds, strlen(creds))); g_options.fetch_opts.custom_headers.count = 1; g_options.fetch_opts.custom_headers.strings = &auth.ptr; cl_git_pass(git_clone(&g_repo, "https://bitbucket.org/libgit2-test/testgitrepository.git", "./foo", &g_options)); git_str_dispose(&auth); } void test_online_clone__bitbucket_style(void) { git_credential_userpass_payload user_pass = { "libgit2-test", "YT77Ppm2nq8w4TYjGS8U" }; g_options.fetch_opts.callbacks.credentials = git_credential_userpass; g_options.fetch_opts.callbacks.payload = &user_pass; cl_git_pass(git_clone(&g_repo, BB_REPO_URL, "./foo", &g_options)); git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup("./foo"); } void test_online_clone__bitbucket_uses_creds_in_url(void) { git_credential_userpass_payload user_pass = { "libgit2-test", "wrong" }; g_options.fetch_opts.callbacks.credentials = git_credential_userpass; g_options.fetch_opts.callbacks.payload = &user_pass; /* * Correct user and pass are in the URL; the (incorrect) creds in * the `git_credential_userpass_payload` should be ignored. */ cl_git_pass(git_clone(&g_repo, BB_REPO_URL_WITH_PASS, "./foo", &g_options)); git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup("./foo"); } void test_online_clone__bitbucket_falls_back_to_specified_creds(void) { git_credential_userpass_payload user_pass = { "libgit2-test", "libgit2" }; g_options.fetch_opts.callbacks.credentials = git_credential_userpass; g_options.fetch_opts.callbacks.payload = &user_pass; /* * TODO: as of March 2018, bitbucket sporadically fails with * 403s instead of replying with a 401 - but only sometimes. */ cl_skip(); /* * Incorrect user and pass are in the URL; the (correct) creds in * the `git_credential_userpass_payload` should be used as a fallback. */ cl_git_pass(git_clone(&g_repo, BB_REPO_URL_WITH_WRONG_PASS, "./foo", &g_options)); git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup("./foo"); } void test_online_clone__googlesource(void) { #ifdef __APPLE__ cl_skip(); #else cl_git_pass(git_clone(&g_repo, GOOGLESOURCE_REPO_URL, "./foo", &g_options)); git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup("./foo"); #endif } static int cancel_at_half(const git_indexer_progress *stats, void *payload) { GIT_UNUSED(payload); if (stats->received_objects > (stats->total_objects/2)) return 4321; return 0; } void test_online_clone__can_cancel(void) { g_options.fetch_opts.callbacks.transfer_progress = cancel_at_half; cl_git_fail_with(4321, git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options)); } static int cred_cb(git_credential **cred, const char *url, const char *user_from_url, unsigned int allowed_types, void *payload) { GIT_UNUSED(url); GIT_UNUSED(user_from_url); GIT_UNUSED(payload); if (allowed_types & GIT_CREDENTIAL_USERNAME) return git_credential_username_new(cred, _remote_user); if (allowed_types & GIT_CREDENTIAL_SSH_KEY) return git_credential_ssh_key_new(cred, _remote_user, _remote_ssh_pubkey, _remote_ssh_privkey, _remote_ssh_passphrase); git_error_set(GIT_ERROR_NET, "unexpected cred type"); return -1; } static int check_ssh_auth_methods(git_credential **cred, const char *url, const char *username_from_url, unsigned int allowed_types, void *data) { int *with_user = (int *) data; GIT_UNUSED(cred); GIT_UNUSED(url); GIT_UNUSED(username_from_url); GIT_UNUSED(data); if (!*with_user) cl_assert_equal_i(GIT_CREDENTIAL_USERNAME, allowed_types); else cl_assert(!(allowed_types & GIT_CREDENTIAL_USERNAME)); return GIT_EUSER; } void test_online_clone__ssh_auth_methods(void) { int with_user; #ifndef GIT_SSH clar__skip(); #endif g_options.fetch_opts.callbacks.credentials = check_ssh_auth_methods; g_options.fetch_opts.callbacks.payload = &with_user; g_options.fetch_opts.callbacks.certificate_check = NULL; with_user = 0; cl_git_fail_with(GIT_EUSER, git_clone(&g_repo, SSH_REPO_URL, "./foo", &g_options)); with_user = 1; cl_git_fail_with(GIT_EUSER, git_clone(&g_repo, "ssh://[email protected]/libgit2/TestGitRepository", "./foo", &g_options)); } static int custom_remote_ssh_with_paths( git_remote **out, git_repository *repo, const char *name, const char *url, void *payload) { int error; GIT_UNUSED(payload); if ((error = git_remote_create(out, repo, name, url)) < 0) return error; return 0; } void test_online_clone__ssh_with_paths(void) { char *bad_paths[] = { "/bin/yes", "/bin/false", }; char *good_paths[] = { "/usr/bin/git-upload-pack", "/usr/bin/git-receive-pack", }; git_strarray arr = { bad_paths, 2, }; #ifndef GIT_SSH clar__skip(); #endif if (!_remote_url || !_remote_user || strncmp(_remote_url, "ssh://", 5) != 0) clar__skip(); g_options.remote_cb = custom_remote_ssh_with_paths; g_options.fetch_opts.callbacks.transport = git_transport_ssh_with_paths; g_options.fetch_opts.callbacks.credentials = cred_cb; g_options.fetch_opts.callbacks.payload = &arr; g_options.fetch_opts.callbacks.certificate_check = NULL; cl_git_fail(git_clone(&g_repo, _remote_url, "./foo", &g_options)); arr.strings = good_paths; cl_git_pass(git_clone(&g_repo, _remote_url, "./foo", &g_options)); } static int cred_foo_bar(git_credential **cred, const char *url, const char *username_from_url, unsigned int allowed_types, void *data) { GIT_UNUSED(url); GIT_UNUSED(username_from_url); GIT_UNUSED(allowed_types); GIT_UNUSED(data); return git_credential_userpass_plaintext_new(cred, "foo", "bar"); } void test_online_clone__ssh_cannot_change_username(void) { #ifndef GIT_SSH clar__skip(); #endif g_options.fetch_opts.callbacks.credentials = cred_foo_bar; cl_git_fail(git_clone(&g_repo, "ssh://[email protected]/libgit2/TestGitRepository", "./foo", &g_options)); } static int ssh_certificate_check(git_cert *cert, int valid, const char *host, void *payload) { git_cert_hostkey *key; git_oid expected = GIT_OID_SHA1_ZERO, actual = GIT_OID_SHA1_ZERO; GIT_UNUSED(valid); GIT_UNUSED(payload); cl_assert(_remote_ssh_fingerprint); cl_git_pass(git_oid__fromstrp(&expected, _remote_ssh_fingerprint, GIT_OID_SHA1)); cl_assert_equal_i(GIT_CERT_HOSTKEY_LIBSSH2, cert->cert_type); key = (git_cert_hostkey *) cert; /* * We need to figure out how long our input was to check for * the type. Here we abuse the fact that both hashes fit into * our git_oid type. */ if (strlen(_remote_ssh_fingerprint) == 32 && key->type & GIT_CERT_SSH_MD5) { memcpy(&actual.id, key->hash_md5, 16); } else if (strlen(_remote_ssh_fingerprint) == 40 && key->type & GIT_CERT_SSH_SHA1) { memcpy(&actual, key->hash_sha1, 20); } else { cl_fail("Cannot find a usable SSH hash"); } cl_assert(!memcmp(&expected, &actual, 20)); cl_assert_equal_s("localhost", host); return GIT_EUSER; } void test_online_clone__ssh_cert(void) { g_options.fetch_opts.callbacks.certificate_check = ssh_certificate_check; if (!_remote_ssh_fingerprint) cl_skip(); cl_git_fail_with(GIT_EUSER, git_clone(&g_repo, _remote_url, "./foo", &g_options)); } static char *read_key_file(const char *path) { FILE *f; char *buf; long key_length; if (!path || !*path) return NULL; cl_assert((f = fopen(path, "r")) != NULL); cl_assert(fseek(f, 0, SEEK_END) != -1); cl_assert((key_length = ftell(f)) != -1); cl_assert(fseek(f, 0, SEEK_SET) != -1); cl_assert((buf = malloc(key_length)) != NULL); cl_assert(fread(buf, key_length, 1, f) == 1); fclose(f); return buf; } static int ssh_memory_cred_cb(git_credential **cred, const char *url, const char *user_from_url, unsigned int allowed_types, void *payload) { GIT_UNUSED(url); GIT_UNUSED(user_from_url); GIT_UNUSED(payload); if (allowed_types & GIT_CREDENTIAL_USERNAME) return git_credential_username_new(cred, _remote_user); if (allowed_types & GIT_CREDENTIAL_SSH_KEY) { char *pubkey = read_key_file(_remote_ssh_pubkey); char *privkey = read_key_file(_remote_ssh_privkey); int ret = git_credential_ssh_key_memory_new(cred, _remote_user, pubkey, privkey, _remote_ssh_passphrase); if (privkey) free(privkey); if (pubkey) free(pubkey); return ret; } git_error_set(GIT_ERROR_NET, "unexpected cred type"); return -1; } void test_online_clone__ssh_memory_auth(void) { #ifndef GIT_SSH_MEMORY_CREDENTIALS clar__skip(); #endif if (!_remote_url || !_remote_user || !_remote_ssh_privkey || strncmp(_remote_url, "ssh://", 5) != 0) clar__skip(); g_options.fetch_opts.callbacks.credentials = ssh_memory_cred_cb; cl_git_pass(git_clone(&g_repo, _remote_url, "./foo", &g_options)); } static int fail_certificate_check(git_cert *cert, int valid, const char *host, void *payload) { GIT_UNUSED(cert); GIT_UNUSED(valid); GIT_UNUSED(host); GIT_UNUSED(payload); return GIT_ECERTIFICATE; } void test_online_clone__certificate_invalid(void) { g_options.fetch_opts.callbacks.certificate_check = fail_certificate_check; cl_git_fail_with(git_clone(&g_repo, "https://github.com/libgit2/TestGitRepository", "./foo", &g_options), GIT_ECERTIFICATE); #ifdef GIT_SSH cl_git_fail_with(git_clone(&g_repo, "ssh://github.com/libgit2/TestGitRepository", "./foo", &g_options), GIT_ECERTIFICATE); #endif } static int succeed_certificate_check(git_cert *cert, int valid, const char *host, void *payload) { GIT_UNUSED(cert); GIT_UNUSED(valid); GIT_UNUSED(payload); cl_assert_equal_s("github.com", host); return 0; } void test_online_clone__certificate_valid(void) { g_options.fetch_opts.callbacks.certificate_check = succeed_certificate_check; cl_git_pass(git_clone(&g_repo, "https://github.com/libgit2/TestGitRepository", "./foo", &g_options)); } void test_online_clone__start_with_http(void) { g_options.fetch_opts.callbacks.certificate_check = succeed_certificate_check; cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options)); } static int called_proxy_creds; static int proxy_cred_cb(git_credential **out, const char *url, const char *username, unsigned int allowed, void *payload) { GIT_UNUSED(url); GIT_UNUSED(username); GIT_UNUSED(allowed); GIT_UNUSED(payload); called_proxy_creds = 1; return git_credential_userpass_plaintext_new(out, _remote_proxy_user, _remote_proxy_pass); } static int proxy_cert_cb(git_cert *cert, int valid, const char *host, void *payload) { char *colon; size_t host_len; GIT_UNUSED(cert); GIT_UNUSED(valid); GIT_UNUSED(payload); cl_assert(_remote_proxy_host); if ((colon = strchr(_remote_proxy_host, ':')) != NULL) host_len = (colon - _remote_proxy_host); else host_len = strlen(_remote_proxy_host); if (_remote_proxy_selfsigned != NULL && strlen(host) == host_len && strncmp(_remote_proxy_host, host, host_len) == 0) valid = 1; return valid ? 0 : GIT_ECERTIFICATE; } void test_online_clone__proxy_credentials_request(void) { git_str url = GIT_STR_INIT; if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass) cl_skip(); cl_git_pass(git_str_printf(&url, "%s://%s/", _remote_proxy_scheme ? _remote_proxy_scheme : "http", _remote_proxy_host)); g_options.fetch_opts.proxy_opts.type = GIT_PROXY_SPECIFIED; g_options.fetch_opts.proxy_opts.url = url.ptr; g_options.fetch_opts.proxy_opts.credentials = proxy_cred_cb; g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb; called_proxy_creds = 0; cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options)); cl_assert(called_proxy_creds); git_str_dispose(&url); } void test_online_clone__proxy_credentials_in_url(void) { git_str url = GIT_STR_INIT; if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass) cl_skip(); cl_git_pass(git_str_printf(&url, "%s://%s:%s@%s/", _remote_proxy_scheme ? _remote_proxy_scheme : "http", _remote_proxy_user, _remote_proxy_pass, _remote_proxy_host)); g_options.fetch_opts.proxy_opts.type = GIT_PROXY_SPECIFIED; g_options.fetch_opts.proxy_opts.url = url.ptr; g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb; called_proxy_creds = 0; cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options)); cl_assert(called_proxy_creds == 0); git_str_dispose(&url); } void test_online_clone__proxy_credentials_in_environment(void) { git_str url = GIT_STR_INIT; if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass) cl_skip(); _orig_http_proxy = cl_getenv("HTTP_PROXY"); _orig_https_proxy = cl_getenv("HTTPS_PROXY"); _orig_no_proxy = cl_getenv("NO_PROXY"); _orig_proxies_need_reset = 1; g_options.fetch_opts.proxy_opts.type = GIT_PROXY_AUTO; g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb; cl_git_pass(git_str_printf(&url, "%s://%s:%s@%s/", _remote_proxy_scheme ? _remote_proxy_scheme : "http", _remote_proxy_user, _remote_proxy_pass, _remote_proxy_host)); cl_setenv("HTTP_PROXY", url.ptr); cl_setenv("HTTPS_PROXY", url.ptr); cl_setenv("NO_PROXY", NULL); cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options)); git_str_dispose(&url); } void test_online_clone__proxy_credentials_in_url_https(void) { git_str url = GIT_STR_INIT; if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass) cl_skip(); cl_git_pass(git_str_printf(&url, "%s://%s:%s@%s/", _remote_proxy_scheme ? _remote_proxy_scheme : "http", _remote_proxy_user, _remote_proxy_pass, _remote_proxy_host)); g_options.fetch_opts.proxy_opts.type = GIT_PROXY_SPECIFIED; g_options.fetch_opts.proxy_opts.url = url.ptr; g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb; g_options.fetch_opts.callbacks.certificate_check = ssl_cert; called_proxy_creds = 0; cl_git_pass(git_clone(&g_repo, "https://github.com/libgit2/TestGitRepository", "./foo", &g_options)); cl_assert(called_proxy_creds == 0); git_str_dispose(&url); } void test_online_clone__proxy_auto_not_detected(void) { g_options.fetch_opts.proxy_opts.type = GIT_PROXY_AUTO; cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options)); } void test_online_clone__proxy_cred_callback_after_failed_url_creds(void) { git_str url = GIT_STR_INIT; if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass) cl_skip(); cl_git_pass(git_str_printf(&url, "%s://invalid_user_name:INVALID_pass_WORD@%s/", _remote_proxy_scheme ? _remote_proxy_scheme : "http", _remote_proxy_host)); g_options.fetch_opts.proxy_opts.type = GIT_PROXY_SPECIFIED; g_options.fetch_opts.proxy_opts.url = url.ptr; g_options.fetch_opts.proxy_opts.credentials = proxy_cred_cb; g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb; called_proxy_creds = 0; cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options)); cl_assert(called_proxy_creds); git_str_dispose(&url); } void test_online_clone__azurerepos(void) { cl_git_pass(git_clone(&g_repo, "https://[email protected]/libgit2/test/_git/test", "./foo", &g_options)); cl_assert(git_fs_path_exists("./foo/master.txt")); } void test_online_clone__path_whitespace(void) { cl_git_pass(git_clone(&g_repo, "https://[email protected]/libgit2/test/_git/spaces%20in%20the%20name", "./foo", &g_options)); cl_assert(git_fs_path_exists("./foo/master.txt")); } void test_online_clone__redirect_default_succeeds_for_initial(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; if (!_remote_redirect_initial || !_remote_redirect_subsequent) cl_skip(); cl_git_pass(git_clone(&g_repo, _remote_redirect_initial, "./initial", &options)); } void test_online_clone__redirect_default_fails_for_subsequent(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; if (!_remote_redirect_initial || !_remote_redirect_subsequent) cl_skip(); cl_git_fail(git_clone(&g_repo, _remote_redirect_subsequent, "./fail", &options)); } void test_online_clone__redirect_none(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; if (!_remote_redirect_initial) cl_skip(); options.fetch_opts.follow_redirects = GIT_REMOTE_REDIRECT_NONE; cl_git_fail(git_clone(&g_repo, _remote_redirect_initial, "./fail", &options)); } void test_online_clone__redirect_initial_succeeds_for_initial(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; if (!_remote_redirect_initial || !_remote_redirect_subsequent) cl_skip(); options.fetch_opts.follow_redirects = GIT_REMOTE_REDIRECT_INITIAL; cl_git_pass(git_clone(&g_repo, _remote_redirect_initial, "./initial", &options)); } void test_online_clone__redirect_initial_fails_for_subsequent(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; if (!_remote_redirect_initial || !_remote_redirect_subsequent) cl_skip(); options.fetch_opts.follow_redirects = GIT_REMOTE_REDIRECT_INITIAL; cl_git_fail(git_clone(&g_repo, _remote_redirect_subsequent, "./fail", &options)); } void test_online_clone__namespace_bare(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; git_reference *head; if (!_remote_url) cl_skip(); options.bare = true; cl_git_pass(git_clone(&g_repo, _remote_url, "./namespaced.git", &options)); cl_git_pass(git_reference_lookup(&head, g_repo, GIT_HEAD_FILE)); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head)); cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head)); git_reference_free(head); } void test_online_clone__namespace_with_specified_branch(void) { git_clone_options options = GIT_CLONE_OPTIONS_INIT; git_reference *head; if (!_remote_url || !_remote_branch) cl_skip(); options.checkout_branch = _remote_branch; cl_git_pass(git_clone(&g_repo, _remote_url, "./namespaced", &options)); cl_git_pass(git_reference_lookup(&head, g_repo, GIT_HEAD_FILE)); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head)); cl_assert_equal_strn("refs/heads/", git_reference_symbolic_target(head), 11); cl_assert_equal_s(_remote_branch, git_reference_symbolic_target(head) + 11); git_reference_free(head); }
libgit2-main
tests/libgit2/online/clone.c
#include "clar_libgit2.h" #include "repository.h" #include "submodule.h" static const char *repo_name = "win32-forbidden"; static git_repository *repo; void test_win32_forbidden__initialize(void) { repo = cl_git_sandbox_init(repo_name); } void test_win32_forbidden__cleanup(void) { cl_git_sandbox_cleanup(); } void test_win32_forbidden__can_open_index(void) { git_index *index; cl_git_pass(git_repository_index(&index, repo)); cl_assert_equal_i(7, git_index_entrycount(index)); /* ensure we can even write the unmodified index */ cl_git_pass(git_index_write(index)); git_index_free(index); } void test_win32_forbidden__can_add_forbidden_filename_with_entry(void) { git_index *index; git_index_entry entry = {{0}}; cl_git_pass(git_repository_index(&index, repo)); entry.path = "aux"; entry.mode = GIT_FILEMODE_BLOB; git_oid__fromstr(&entry.id, "da623abd956bb2fd8052c708c7ed43f05d192d37", GIT_OID_SHA1); cl_git_pass(git_index_add(index, &entry)); git_index_free(index); } void test_win32_forbidden__cannot_add_dot_git_even_with_entry(void) { git_index *index; git_index_entry entry = {{0}}; cl_git_pass(git_repository_index(&index, repo)); entry.path = "foo/.git"; entry.mode = GIT_FILEMODE_BLOB; git_oid__fromstr(&entry.id, "da623abd956bb2fd8052c708c7ed43f05d192d37", GIT_OID_SHA1); cl_git_fail(git_index_add(index, &entry)); git_index_free(index); } void test_win32_forbidden__cannot_add_forbidden_filename_from_filesystem(void) { git_index *index; /* since our function calls are very low-level, we can create `aux.`, * but we should not be able to add it to the index */ cl_git_pass(git_repository_index(&index, repo)); cl_git_write2file("win32-forbidden/aux.", "foo\n", 4, O_RDWR | O_CREAT, 0666); #ifdef GIT_WIN32 cl_git_fail(git_index_add_bypath(index, "aux.")); #else cl_git_pass(git_index_add_bypath(index, "aux.")); #endif cl_must_pass(p_unlink("win32-forbidden/aux.")); git_index_free(index); } static int dummy_submodule_cb( git_submodule *sm, const char *name, void *payload) { GIT_UNUSED(sm); GIT_UNUSED(name); GIT_UNUSED(payload); return 0; } void test_win32_forbidden__can_diff_tree_to_index(void) { git_diff *diff; git_tree *tree; cl_git_pass(git_repository_head_tree(&tree, repo)); cl_git_pass(git_diff_tree_to_index(&diff, repo, tree, NULL, NULL)); cl_assert_equal_i(0, git_diff_num_deltas(diff)); git_diff_free(diff); git_tree_free(tree); } void test_win32_forbidden__can_diff_tree_to_tree(void) { git_diff *diff; git_tree *tree; cl_git_pass(git_repository_head_tree(&tree, repo)); cl_git_pass(git_diff_tree_to_tree(&diff, repo, tree, tree, NULL)); cl_assert_equal_i(0, git_diff_num_deltas(diff)); git_diff_free(diff); git_tree_free(tree); } void test_win32_forbidden__can_diff_index_to_workdir(void) { git_index *index; git_diff *diff; const git_diff_delta *delta; git_tree *tree; size_t i; cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_repository_head_tree(&tree, repo)); cl_git_pass(git_diff_index_to_workdir(&diff, repo, index, NULL)); for (i = 0; i < git_diff_num_deltas(diff); i++) { delta = git_diff_get_delta(diff, i); cl_assert_equal_i(GIT_DELTA_DELETED, delta->status); } git_diff_free(diff); git_tree_free(tree); git_index_free(index); } void test_win32_forbidden__checking_out_forbidden_index_fails(void) { #ifdef GIT_WIN32 git_index *index; git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; git_diff *diff; const git_diff_delta *delta; git_tree *tree; size_t num_deltas, i; opts.checkout_strategy = GIT_CHECKOUT_FORCE; cl_git_pass(git_repository_index(&index, repo)); cl_git_fail(git_checkout_index(repo, index, &opts)); cl_git_pass(git_repository_head_tree(&tree, repo)); cl_git_pass(git_diff_index_to_workdir(&diff, repo, index, NULL)); num_deltas = git_diff_num_deltas(diff); cl_assert(num_deltas > 0); for (i = 0; i < num_deltas; i++) { delta = git_diff_get_delta(diff, i); cl_assert_equal_i(GIT_DELTA_DELETED, delta->status); } git_diff_free(diff); git_tree_free(tree); git_index_free(index); #endif } void test_win32_forbidden__can_query_submodules(void) { cl_git_pass(git_submodule_foreach(repo, dummy_submodule_cb, NULL)); } void test_win32_forbidden__can_blame_file(void) { git_blame *blame; cl_git_pass(git_blame_file(&blame, repo, "aux", NULL)); git_blame_free(blame); }
libgit2-main
tests/libgit2/win32/forbidden.c
#include "clar_libgit2.h" #include "futils.h" #include "sysdir.h" #include "win32/findfile.h" #ifdef GIT_WIN32 static char *path_save; static git_str gfw_path_root = GIT_STR_INIT; static git_str gfw_registry_root = GIT_STR_INIT; #endif void test_win32_systemdir__initialize(void) { #ifdef GIT_WIN32 git_str path_env = GIT_STR_INIT; path_save = cl_getenv("PATH"); git_win32__set_registry_system_dir(L""); cl_git_pass(git_str_puts(&path_env, "C:\\GitTempTest\\Foo;\"c:\\program files\\doesnotexisttesttemp\";C:\\fakefakedoesnotexist")); cl_setenv("PATH", path_env.ptr); cl_git_pass(git_str_puts(&gfw_path_root, clar_sandbox_path())); cl_git_pass(git_str_puts(&gfw_path_root, "/fake_gfw_path_install")); cl_git_pass(git_str_puts(&gfw_registry_root, clar_sandbox_path())); cl_git_pass(git_str_puts(&gfw_registry_root, "/fake_gfw_registry_install")); git_str_dispose(&path_env); #endif } void test_win32_systemdir__cleanup(void) { #ifdef GIT_WIN32 cl_fixture_cleanup("fake_gfw_path_install"); cl_fixture_cleanup("fake_gfw_registry_install"); git_str_dispose(&gfw_path_root); git_str_dispose(&gfw_registry_root); cl_setenv("PATH", path_save); git__free(path_save); path_save = NULL; git_win32__set_registry_system_dir(NULL); cl_sandbox_set_search_path_defaults(); #endif } #ifdef GIT_WIN32 static void fix_path(git_str *s) { char *c; for (c = s->ptr; *c; c++) { if (*c == '/') *c = '\\'; } } static void populate_fake_gfw( git_str *expected_etc_dir, const char *root, const char *token, bool create_gitconfig, bool create_mingw64_gitconfig, bool add_to_path, bool add_to_registry) { git_str bin_path = GIT_STR_INIT, exe_path = GIT_STR_INIT, etc_path = GIT_STR_INIT, mingw64_path = GIT_STR_INIT, config_path = GIT_STR_INIT, path_env = GIT_STR_INIT, config_data = GIT_STR_INIT; cl_git_pass(git_str_puts(&bin_path, root)); cl_git_pass(git_str_puts(&bin_path, "/cmd")); cl_git_pass(git_futils_mkdir_r(bin_path.ptr, 0755)); cl_git_pass(git_str_puts(&exe_path, bin_path.ptr)); cl_git_pass(git_str_puts(&exe_path, "/git.cmd")); cl_git_mkfile(exe_path.ptr, "This is a fake executable."); cl_git_pass(git_str_puts(&etc_path, root)); cl_git_pass(git_str_puts(&etc_path, "/etc")); cl_git_pass(git_futils_mkdir_r(etc_path.ptr, 0755)); cl_git_pass(git_str_puts(&mingw64_path, root)); cl_git_pass(git_str_puts(&mingw64_path, "/mingw64/etc")); cl_git_pass(git_futils_mkdir_r(mingw64_path.ptr, 0755)); if (create_gitconfig) { git_str_clear(&config_data); git_str_printf(&config_data, "[gfw]\n\ttest = etc %s\n", token); cl_git_pass(git_str_puts(&config_path, etc_path.ptr)); cl_git_pass(git_str_puts(&config_path, "/gitconfig")); cl_git_mkfile(config_path.ptr, config_data.ptr); } if (create_mingw64_gitconfig) { git_str_clear(&config_data); git_str_printf(&config_data, "[gfw]\n\ttest = mingw64 %s\n", token); git_str_clear(&config_path); cl_git_pass(git_str_puts(&config_path, mingw64_path.ptr)); cl_git_pass(git_str_puts(&config_path, "/gitconfig")); cl_git_mkfile(config_path.ptr, config_data.ptr); } if (add_to_path) { fix_path(&bin_path); cl_git_pass(git_str_puts(&path_env, "C:\\GitTempTest\\Foo;\"c:\\program files\\doesnotexisttesttemp\";")); cl_git_pass(git_str_puts(&path_env, bin_path.ptr)); cl_git_pass(git_str_puts(&path_env, ";C:\\fakefakedoesnotexist")); cl_setenv("PATH", path_env.ptr); } if (add_to_registry) { git_win32_path registry_path; size_t offset = 0; cl_assert(git_win32_path_from_utf8(registry_path, root) >= 0); if (wcsncmp(registry_path, L"\\\\?\\", CONST_STRLEN("\\\\?\\")) == 0) offset = CONST_STRLEN("\\\\?\\"); git_win32__set_registry_system_dir(registry_path + offset); } cl_git_pass(git_str_join(expected_etc_dir, GIT_PATH_LIST_SEPARATOR, expected_etc_dir->ptr, etc_path.ptr)); cl_git_pass(git_str_join(expected_etc_dir, GIT_PATH_LIST_SEPARATOR, expected_etc_dir->ptr, mingw64_path.ptr)); git_str_dispose(&bin_path); git_str_dispose(&exe_path); git_str_dispose(&etc_path); git_str_dispose(&mingw64_path); git_str_dispose(&config_path); git_str_dispose(&path_env); git_str_dispose(&config_data); } static void populate_fake_ecosystem( git_str *expected_etc_dir, bool create_gitconfig, bool create_mingw64_gitconfig, bool path, bool registry) { if (path) populate_fake_gfw(expected_etc_dir, gfw_path_root.ptr, "path", create_gitconfig, create_mingw64_gitconfig, true, false); if (registry) populate_fake_gfw(expected_etc_dir, gfw_registry_root.ptr, "registry", create_gitconfig, create_mingw64_gitconfig, false, true); } #endif void test_win32_systemdir__finds_etc_in_path(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config *cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, true, false, true, false); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("etc path", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__finds_mingw64_etc_in_path(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config* cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, false, true, true, false); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("mingw64 path", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__prefers_etc_to_mingw64_in_path(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config* cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, true, true, true, false); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("etc path", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__finds_etc_in_registry(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config* cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, true, false, false, true); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("etc registry", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__finds_mingw64_etc_in_registry(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config* cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, false, true, false, true); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("mingw64 registry", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__prefers_etc_to_mingw64_in_registry(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config* cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, true, true, false, true); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("etc registry", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__prefers_path_to_registry(void) { #ifdef GIT_WIN32 git_str expected = GIT_STR_INIT, out = GIT_STR_INIT; git_config* cfg; git_buf value = GIT_BUF_INIT; populate_fake_ecosystem(&expected, true, true, true, true); cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, expected.ptr); git_sysdir_reset(); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_string_buf(&value, cfg, "gfw.test")); cl_assert_equal_s("etc path", value.ptr); git_buf_dispose(&value); git_str_dispose(&expected); git_str_dispose(&out); git_config_free(cfg); #endif } void test_win32_systemdir__no_git_installed(void) { #ifdef GIT_WIN32 git_str out = GIT_STR_INIT; cl_git_pass(git_win32__find_system_dirs(&out, "etc")); cl_assert_equal_s(out.ptr, ""); #endif }
libgit2-main
tests/libgit2/win32/systemdir.c
#include "clar_libgit2.h" #include "git2/clone.h" #include "clone.h" #include "futils.h" #include "repository.h" static git_str path = GIT_STR_INIT; #define LONG_FILENAME "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.txt" void test_win32_longpath__initialize(void) { #ifdef GIT_WIN32 const char *base = clar_sandbox_path(); size_t base_len = strlen(base); size_t remain = MAX_PATH - base_len; size_t i; git_str_clear(&path); git_str_puts(&path, base); git_str_putc(&path, '/'); cl_assert(remain < (MAX_PATH - 5)); for (i = 0; i < (remain - 5); i++) git_str_putc(&path, 'a'); #endif } void test_win32_longpath__cleanup(void) { git_str_dispose(&path); cl_git_sandbox_cleanup(); } void test_win32_longpath__errmsg_on_checkout(void) { #ifdef GIT_WIN32 git_repository *repo; cl_git_fail(git_clone(&repo, cl_fixture("testrepo.git"), path.ptr, NULL)); cl_assert(git__prefixcmp(git_error_last()->message, "path too long") == 0); #endif } void test_win32_longpath__workdir_path_validated(void) { #ifdef GIT_WIN32 git_repository *repo = cl_git_sandbox_init("testrepo"); git_str out = GIT_STR_INIT; cl_git_pass(git_repository_workdir_path(&out, repo, "a.txt")); /* even if the repo path is a drive letter, this is too long */ cl_git_fail(git_repository_workdir_path(&out, repo, LONG_FILENAME)); cl_assert(git__prefixcmp(git_error_last()->message, "path too long") == 0); cl_repo_set_bool(repo, "core.longpaths", true); cl_git_pass(git_repository_workdir_path(&out, repo, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.txt")); cl_git_pass(git_repository_workdir_path(&out, repo, LONG_FILENAME)); git_str_dispose(&out); #endif } #ifdef GIT_WIN32 static void assert_longpath_status_and_add(git_repository *repo, const char *wddata, const char *repodata) { git_index *index; git_blob *blob; git_str out = GIT_STR_INIT; const git_index_entry *entry; unsigned int status_flags; cl_git_pass(git_repository_workdir_path(&out, repo, LONG_FILENAME)); cl_git_rewritefile(out.ptr, wddata); cl_git_pass(git_status_file(&status_flags, repo, LONG_FILENAME)); cl_assert_equal_i(GIT_STATUS_WT_NEW, status_flags); cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_add_bypath(index, LONG_FILENAME)); cl_git_pass(git_status_file(&status_flags, repo, LONG_FILENAME)); cl_assert_equal_i(GIT_STATUS_INDEX_NEW, status_flags); cl_assert((entry = git_index_get_bypath(index, LONG_FILENAME, 0)) != NULL); cl_git_pass(git_blob_lookup(&blob, repo, &entry->id)); cl_assert_equal_s(repodata, git_blob_rawcontent(blob)); git_blob_free(blob); git_index_free(index); git_str_dispose(&out); } #endif void test_win32_longpath__status_and_add(void) { #ifdef GIT_WIN32 git_repository *repo = cl_git_sandbox_init("testrepo"); cl_repo_set_bool(repo, "core.longpaths", true); /* * Doing no content filtering, we expect the data we add * to be the data in the repository. */ assert_longpath_status_and_add(repo, "This is a long path.\r\n", "This is a long path.\r\n"); #endif } void test_win32_longpath__status_and_add_with_filter(void) { #ifdef GIT_WIN32 git_repository *repo = cl_git_sandbox_init("testrepo"); cl_repo_set_bool(repo, "core.longpaths", true); cl_repo_set_bool(repo, "core.autocrlf", true); /* * With `core.autocrlf`, we expect the data we add to have * newline conversion performed. */ assert_longpath_status_and_add(repo, "This is a long path.\r\n", "This is a long path.\n"); #endif }
libgit2-main
tests/libgit2/win32/longpath.c
#include "clar_libgit2.h" #include "helper__perf__timer.h" #if defined(GIT_WIN32) void perf__timer__start(perf_timer *t) { QueryPerformanceCounter(&t->time_started); } void perf__timer__stop(perf_timer *t) { LARGE_INTEGER time_now; QueryPerformanceCounter(&time_now); t->sum.QuadPart += (time_now.QuadPart - t->time_started.QuadPart); } void perf__timer__report(perf_timer *t, const char *fmt, ...) { va_list arglist; LARGE_INTEGER freq; double fraction; QueryPerformanceFrequency(&freq); fraction = ((double)t->sum.QuadPart) / ((double)freq.QuadPart); printf("%10.3f: ", fraction); va_start(arglist, fmt); vprintf(fmt, arglist); va_end(arglist); printf("\n"); } #else #include <sys/time.h> static uint32_t now_in_ms(void) { struct timeval now; gettimeofday(&now, NULL); return (uint32_t)((now.tv_sec * 1000) + (now.tv_usec / 1000)); } void perf__timer__start(perf_timer *t) { t->time_started = now_in_ms(); } void perf__timer__stop(perf_timer *t) { uint32_t now = now_in_ms(); t->sum += (now - t->time_started); } void perf__timer__report(perf_timer *t, const char *fmt, ...) { va_list arglist; printf("%10.3f: ", ((double)t->sum) / 1000); va_start(arglist, fmt); vprintf(fmt, arglist); va_end(arglist); printf("\n"); } #endif
libgit2-main
tests/libgit2/perf/helper__perf__timer.c
#include "clar_libgit2.h" #include "helper__perf__do_merge.h" #include "helper__perf__timer.h" static git_repository * g_repo; void perf__do_merge(const char *fixture, const char *test_name, const char *id_a, const char *id_b) { git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT; git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT; git_oid oid_a; git_oid oid_b; git_reference *ref_branch_a = NULL; git_reference *ref_branch_b = NULL; git_commit *commit_a = NULL; git_commit *commit_b = NULL; git_annotated_commit *annotated_commits[1] = { NULL }; perf_timer t_total = PERF_TIMER_INIT; perf_timer t_clone = PERF_TIMER_INIT; perf_timer t_checkout = PERF_TIMER_INIT; perf_timer t_merge = PERF_TIMER_INIT; perf__timer__start(&t_total); checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; clone_opts.checkout_opts = checkout_opts; perf__timer__start(&t_clone); cl_git_pass(git_clone(&g_repo, fixture, test_name, &clone_opts)); perf__timer__stop(&t_clone); git_oid__fromstr(&oid_a, id_a, GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit_a, g_repo, &oid_a)); cl_git_pass(git_branch_create(&ref_branch_a, g_repo, "A", commit_a, 0)); perf__timer__start(&t_checkout); cl_git_pass(git_checkout_tree(g_repo, (git_object*)commit_a, &checkout_opts)); perf__timer__stop(&t_checkout); cl_git_pass(git_repository_set_head(g_repo, git_reference_name(ref_branch_a))); git_oid__fromstr(&oid_b, id_b, GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit_b, g_repo, &oid_b)); cl_git_pass(git_branch_create(&ref_branch_b, g_repo, "B", commit_b, 0)); cl_git_pass(git_annotated_commit_lookup(&annotated_commits[0], g_repo, &oid_b)); perf__timer__start(&t_merge); cl_git_pass(git_merge(g_repo, (const git_annotated_commit **)annotated_commits, 1, &merge_opts, &checkout_opts)); perf__timer__stop(&t_merge); git_reference_free(ref_branch_a); git_reference_free(ref_branch_b); git_commit_free(commit_a); git_commit_free(commit_b); git_annotated_commit_free(annotated_commits[0]); git_repository_free(g_repo); perf__timer__stop(&t_total); perf__timer__report(&t_clone, "%s: clone", test_name); perf__timer__report(&t_checkout, "%s: checkout", test_name); perf__timer__report(&t_merge, "%s: merge", test_name); perf__timer__report(&t_total, "%s: total", test_name); }
libgit2-main
tests/libgit2/perf/helper__perf__do_merge.c
#include "clar_libgit2.h" #include "helper__perf__do_merge.h" /* This test requires a large repo with many files. * It doesn't care about the contents, just the size. * * For now, we use the LibGit2 repo containing the * source tree because it is already here. * * `find . | wc -l` reports 5128. * */ #define SRC_REPO (cl_fixture("../..")) /* We need 2 arbitrary commits within that repo * that have a large number of changed files. * Again, we don't care about the actual contents, * just the size. * * For now, we use these public branches: * maint/v0.21 d853fb9f24e0fe63b3dce9fbc04fd9cfe17a030b Always checkout with case sensitive iterator * maint/v0.22 1ce9ea3ba9b4fa666602d52a5281d41a482cc58b checkout tests: cleanup realpath impl on Win32 * */ #define ID_BRANCH_A "d853fb9f24e0fe63b3dce9fbc04fd9cfe17a030b" #define ID_BRANCH_B "1ce9ea3ba9b4fa666602d52a5281d41a482cc58b" void test_perf_merge__m1(void) { perf__do_merge(SRC_REPO, "m1", ID_BRANCH_A, ID_BRANCH_B); }
libgit2-main
tests/libgit2/perf/merge.c
#include "clar_libgit2.h" #include "git2/rebase.h" #include "posix.h" #include <fcntl.h> static git_repository *repo; static git_signature *signature; /* Fixture setup and teardown */ void test_rebase_inmemory__initialize(void) { repo = cl_git_sandbox_init("rebase"); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1405694510, 0)); } void test_rebase_inmemory__cleanup(void) { git_signature_free(signature); cl_git_sandbox_cleanup(); } void test_rebase_inmemory__not_in_rebase_state(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_options opts = GIT_REBASE_OPTIONS_INIT; opts.inmemory = true; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &opts)); cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); git_rebase_free(rebase); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); } void test_rebase_inmemory__can_resolve_conflicts(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_status_list *status_list; git_oid pick_id, commit_id, expected_commit_id; git_index *rebase_index, *repo_index; git_index_entry resolution = {{0}}; git_rebase_options opts = GIT_REBASE_OPTIONS_INIT; opts.inmemory = true; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/asparagus")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); git_oid__fromstr(&pick_id, "33f915f9e4dbd9f4b24430e48731a59b45b15500", GIT_OID_SHA1); cl_assert_equal_i(GIT_REBASE_OPERATION_PICK, rebase_operation->type); cl_assert_equal_oid(&pick_id, &rebase_operation->id); /* ensure that we did not do anything stupid to the workdir or repo index */ cl_git_pass(git_repository_index(&repo_index, repo)); cl_assert(!git_index_has_conflicts(repo_index)); cl_git_pass(git_status_list_new(&status_list, repo, NULL)); cl_assert_equal_i(0, git_status_list_entrycount(status_list)); /* but that the index returned from rebase does have conflicts */ cl_git_pass(git_rebase_inmemory_index(&rebase_index, rebase)); cl_assert(git_index_has_conflicts(rebase_index)); cl_git_fail_with(GIT_EUNMERGED, git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); /* ensure that we can work with the in-memory index to resolve the conflict */ resolution.path = "asparagus.txt"; resolution.mode = GIT_FILEMODE_BLOB; git_oid__fromstr(&resolution.id, "414dfc71ead79c07acd4ea47fecf91f289afc4b9", GIT_OID_SHA1); cl_git_pass(git_index_conflict_remove(rebase_index, "asparagus.txt")); cl_git_pass(git_index_add(rebase_index, &resolution)); /* and finally create a commit for the resolved rebase operation */ cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_oid__fromstr(&expected_commit_id, "db7af47222181e548810da2ab5fec0e9357c5637", GIT_OID_SHA1)); cl_assert_equal_oid(&commit_id, &expected_commit_id); git_status_list_free(status_list); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_index_free(repo_index); git_index_free(rebase_index); git_rebase_free(rebase); } void test_rebase_inmemory__no_common_ancestor(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_final_id; git_rebase_options opts = GIT_REBASE_OPTIONS_INIT; opts.inmemory = true; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/barley")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_finish(rebase, signature)); git_oid__fromstr(&expected_final_id, "71e7ee8d4fe7d8bf0d107355197e0a953dfdb7f3", GIT_OID_SHA1); cl_assert_equal_oid(&expected_final_id, &commit_id); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_inmemory__with_directories(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, tree_id; git_commit *commit; git_rebase_options opts = GIT_REBASE_OPTIONS_INIT; opts.inmemory = true; git_oid__fromstr(&tree_id, "a4d6d9c3d57308fd8e320cf2525bae8f1adafa57", GIT_OID_SHA1); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/deep_gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_oid(&tree_id, git_commit_tree_id(commit)); git_commit_free(commit); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); }
libgit2-main
tests/libgit2/rebase/inmemory.c
#include "clar_libgit2.h" #include "git2/rebase.h" #include "merge.h" #include "posix.h" #include "annotated_commit.h" #include <fcntl.h> static git_repository *repo; /* Fixture setup and teardown */ void test_rebase_abort__initialize(void) { repo = cl_git_sandbox_init("rebase"); } void test_rebase_abort__cleanup(void) { cl_git_sandbox_cleanup(); } static void ensure_aborted( git_annotated_commit *branch, git_annotated_commit *onto) { git_reference *head_ref, *branch_ref = NULL; git_status_list *statuslist; git_reflog *reflog; const git_reflog_entry *reflog_entry; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); /* Make sure the refs are updated appropriately */ cl_git_pass(git_reference_lookup(&head_ref, repo, "HEAD")); if (branch->ref_name == NULL) cl_assert_equal_oid(git_annotated_commit_id(branch), git_reference_target(head_ref)); else { cl_assert_equal_s("refs/heads/beef", git_reference_symbolic_target(head_ref)); cl_git_pass(git_reference_lookup(&branch_ref, repo, git_reference_symbolic_target(head_ref))); cl_assert_equal_oid(git_annotated_commit_id(branch), git_reference_target(branch_ref)); } git_status_list_new(&statuslist, repo, NULL); cl_assert_equal_i(0, git_status_list_entrycount(statuslist)); git_status_list_free(statuslist); /* Make sure the reflogs are updated appropriately */ cl_git_pass(git_reflog_read(&reflog, repo, "HEAD")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(git_annotated_commit_id(onto), git_reflog_entry_id_old(reflog_entry)); cl_assert_equal_oid(git_annotated_commit_id(branch), git_reflog_entry_id_new(reflog_entry)); cl_assert_equal_s("rebase: aborting", git_reflog_entry_message(reflog_entry)); git_reflog_free(reflog); git_reference_free(head_ref); git_reference_free(branch_ref); } static void test_abort( git_annotated_commit *branch, git_annotated_commit *onto) { git_rebase *rebase; cl_git_pass(git_rebase_open(&rebase, repo, NULL)); cl_git_pass(git_rebase_abort(rebase)); ensure_aborted(branch, onto); git_rebase_free(rebase); } void test_rebase_abort__merge(void) { git_rebase *rebase; git_reference *branch_ref, *onto_ref; git_annotated_commit *branch_head, *onto_head; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&onto_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&onto_head, repo, onto_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); test_abort(branch_head, onto_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_reference_free(branch_ref); git_reference_free(onto_ref); git_rebase_free(rebase); } void test_rebase_abort__merge_immediately_after_init(void) { git_rebase *rebase; git_reference *branch_ref, *onto_ref; git_annotated_commit *branch_head, *onto_head; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&onto_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&onto_head, repo, onto_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_git_pass(git_rebase_abort(rebase)); ensure_aborted(branch_head, onto_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_reference_free(branch_ref); git_reference_free(onto_ref); git_rebase_free(rebase); } void test_rebase_abort__merge_by_id(void) { git_rebase *rebase; git_oid branch_id, onto_id; git_annotated_commit *branch_head, *onto_head; cl_git_pass(git_oid__fromstr(&branch_id, "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&onto_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_lookup(&onto_head, repo, &onto_id)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); test_abort(branch_head, onto_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_rebase_free(rebase); } void test_rebase_abort__merge_by_revspec(void) { git_rebase *rebase; git_annotated_commit *branch_head, *onto_head; cl_git_pass(git_annotated_commit_from_revspec(&branch_head, repo, "b146bd7")); cl_git_pass(git_annotated_commit_from_revspec(&onto_head, repo, "efad0b1")); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); test_abort(branch_head, onto_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_rebase_free(rebase); } void test_rebase_abort__merge_by_id_immediately_after_init(void) { git_rebase *rebase; git_oid branch_id, onto_id; git_annotated_commit *branch_head, *onto_head; cl_git_pass(git_oid__fromstr(&branch_id, "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&onto_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_lookup(&onto_head, repo, &onto_id)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_git_pass(git_rebase_abort(rebase)); ensure_aborted(branch_head, onto_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_rebase_free(rebase); } void test_rebase_abort__detached_head(void) { git_rebase *rebase; git_oid branch_id, onto_id; git_signature *signature; git_annotated_commit *branch_head, *onto_head; git_oid__fromstr(&branch_id, "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1); git_oid__fromstr(&onto_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_lookup(&onto_head, repo, &onto_id)); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1404157834, -400)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); test_abort(branch_head, onto_head); git_signature_free(signature); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_rebase_free(rebase); } void test_rebase_abort__old_style_head_file(void) { git_rebase *rebase; git_reference *branch_ref, *onto_ref; git_signature *signature; git_annotated_commit *branch_head, *onto_head; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&onto_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&onto_head, repo, onto_ref)); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1404157834, -400)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); p_rename("rebase-merge/.git/rebase-merge/orig-head", "rebase-merge/.git/rebase-merge/head"); test_abort(branch_head, onto_head); git_signature_free(signature); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_reference_free(branch_ref); git_reference_free(onto_ref); git_rebase_free(rebase); }
libgit2-main
tests/libgit2/rebase/abort.c
#include "clar_libgit2.h" #include "git2/rebase.h" #include "posix.h" #include <fcntl.h> static git_repository *repo; static git_index *_index; static git_signature *signature; /* Fixture setup and teardown */ void test_rebase_iterator__initialize(void) { repo = cl_git_sandbox_init("rebase"); cl_git_pass(git_repository_index(&_index, repo)); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1405694510, 0)); } void test_rebase_iterator__cleanup(void) { git_signature_free(signature); git_index_free(_index); cl_git_sandbox_cleanup(); } static void test_operations(git_rebase *rebase, size_t expected_current) { size_t i, expected_count = 5; git_oid expected_oid[5]; git_rebase_operation *operation; git_oid__fromstr(&expected_oid[0], "da9c51a23d02d931a486f45ad18cda05cf5d2b94", GIT_OID_SHA1); git_oid__fromstr(&expected_oid[1], "8d1f13f93c4995760ac07d129246ac1ff64c0be9", GIT_OID_SHA1); git_oid__fromstr(&expected_oid[2], "3069cc907e6294623e5917ef6de663928c1febfb", GIT_OID_SHA1); git_oid__fromstr(&expected_oid[3], "588e5d2f04d49707fe4aab865e1deacaf7ef6787", GIT_OID_SHA1); git_oid__fromstr(&expected_oid[4], "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1); cl_assert_equal_i(expected_count, git_rebase_operation_entrycount(rebase)); cl_assert_equal_i(expected_current, git_rebase_operation_current(rebase)); for (i = 0; i < expected_count; i++) { operation = git_rebase_operation_byindex(rebase, i); cl_assert_equal_i(GIT_REBASE_OPERATION_PICK, operation->type); cl_assert_equal_oid(&expected_oid[i], &operation->id); cl_assert_equal_p(NULL, operation->exec); } } static void test_iterator(bool inmemory) { git_rebase *rebase; git_rebase_options opts = GIT_REBASE_OPTIONS_INIT; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_id; int error; opts.inmemory = inmemory; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &opts)); test_operations(rebase, GIT_REBASE_NO_OPERATION); if (!inmemory) { git_rebase_free(rebase); cl_git_pass(git_rebase_open(&rebase, repo, NULL)); } cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); test_operations(rebase, 0); git_oid__fromstr(&expected_id, "776e4c48922799f903f03f5f6e51da8b01e4cce0", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); test_operations(rebase, 1); git_oid__fromstr(&expected_id, "ba1f9b4fd5cf8151f7818be2111cc0869f1eb95a", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); test_operations(rebase, 2); git_oid__fromstr(&expected_id, "948b12fe18b84f756223a61bece4c307787cd5d4", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); if (!inmemory) { git_rebase_free(rebase); cl_git_pass(git_rebase_open(&rebase, repo, NULL)); } cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); test_operations(rebase, 3); git_oid__fromstr(&expected_id, "d9d5d59d72c9968687f9462578d79878cd80e781", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); test_operations(rebase, 4); git_oid__fromstr(&expected_id, "9cf383c0a125d89e742c5dec58ed277dd07588b3", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_fail(error = git_rebase_next(&rebase_operation, rebase)); cl_assert_equal_i(GIT_ITEROVER, error); test_operations(rebase, 4); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_iterator__iterates(void) { test_iterator(false); } void test_rebase_iterator__iterates_inmemory(void) { test_iterator(true); }
libgit2-main
tests/libgit2/rebase/iterator.c
#include "clar_libgit2.h" #include "git2/rebase.h" static git_repository *repo; static git_signature *signature; /* Fixture setup and teardown */ void test_rebase_sign__initialize(void) { repo = cl_git_sandbox_init("rebase"); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1405694510, 0)); } void test_rebase_sign__cleanup(void) { git_signature_free(signature); cl_git_sandbox_cleanup(); } static int create_cb_passthrough( git_oid *out, const git_signature *author, const git_signature *committer, const char *message_encoding, const char *message, const git_tree *tree, size_t parent_count, const git_commit *parents[], void *payload) { GIT_UNUSED(out); GIT_UNUSED(author); GIT_UNUSED(committer); GIT_UNUSED(message_encoding); GIT_UNUSED(message); GIT_UNUSED(tree); GIT_UNUSED(parent_count); GIT_UNUSED(parents); GIT_UNUSED(payload); return GIT_PASSTHROUGH; } /* git checkout gravy ; git rebase --merge veal */ void test_rebase_sign__passthrough_create_cb(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_id; git_rebase_options rebase_opts = GIT_REBASE_OPTIONS_INIT; git_commit *commit; const char *expected_commit_raw_header = "tree cd99b26250099fc38d30bfaed7797a7275ed3366\n\ parent f87d14a4a236582a0278a916340a793714256864\n\ author Edward Thomson <[email protected]> 1405625055 -0400\n\ committer Rebaser <[email protected]> 1405694510 +0000\n"; rebase_opts.commit_create_cb = create_cb_passthrough; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_oid__fromstr(&expected_id, "129183968a65abd6c52da35bff43325001bfc630", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_s(expected_commit_raw_header, git_commit_raw_header(commit)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_commit_free(commit); git_rebase_free(rebase); } static int create_cb_signed_gpg( git_oid *out, const git_signature *author, const git_signature *committer, const char *message_encoding, const char *message, const git_tree *tree, size_t parent_count, const git_commit *parents[], void *payload) { git_buf commit_content = GIT_BUF_INIT; const char *gpg_signature = "-----BEGIN PGP SIGNATURE-----\n\ \n\ iQIzBAEBCgAdFiEEgVlDEfSlmKn0fvGgK++h5T2/ctIFAlwZcrAACgkQK++h5T2/\n\ ctIPVhAA42RyZhMdKl5Bm0KtQco2scsukIg2y7tjSwhti91zDu3HQgpusjjo0fQx\n\ ZzB+OrmlvQ9CDcGpZ0THIzXD8GRJoDMPqdrvZVrBWkGcHvw7/YPA8skzsjkauJ8W\n\ 7lzF5LCuHSS6OUmPT/+5hEHPin5PB3zhfszyC+Q7aujnIuPJMrKiMnUa+w1HWifM\n\ km49OOygQ9S6NQoVuEQede22+c76DlDL7yFghGoo1f0sKCE/9LW6SEnwI/bWv9eo\n\ nom5vOPrvQeJiYCQk+2DyWo8RdSxINtY+G9bPE4RXm+6ZgcXECPm9TYDIWpL36fC\n\ jvtGLs98woWFElOziBMp5Tb630GMcSI+q5ivHfJ3WS5NKLYLHBNK4iSFN0/dgAnB\n\ dj6GcKXKWnIBWn6ZM4o40pcM5KSRUUCLtA0ZmjJH4c4zx3X5fUxd+enwkf3e9VZO\n\ fNKC/+xfq6NfoPUPK9+UnchHpJaJw7RG5tZS+sWCz2xpQ1y3/o49xImNyM3wnpvB\n\ cRAZabqIHpZa9/DIUkELOtCzln6niqkjRgg3M/YCCNznwV+0RNgz87VtyTPerdef\n\ xrqn0+ROMF6ebVqIs6PPtuPkxnAJu7TMKXVB5rFnAewS24e6cIGFzeIA7810py3l\n\ cttVRsdOoego+fiy08eFE+aJIeYiINRGhqOBTsuqG4jIdpdKxPE=\n\ =KbsY\n\ -----END PGP SIGNATURE-----"; git_repository *repo = (git_repository *)payload; int error; if ((error = git_commit_create_buffer(&commit_content, repo, author, committer, message_encoding, message, tree, parent_count, parents)) < 0) goto done; error = git_commit_create_with_signature(out, repo, commit_content.ptr, gpg_signature, NULL); done: git_buf_dispose(&commit_content); return error; } /* git checkout gravy ; git rebase --merge veal */ void test_rebase_sign__create_gpg_signed(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_id; git_rebase_options rebase_opts = GIT_REBASE_OPTIONS_INIT; git_commit *commit; const char *expected_commit_raw_header = "tree cd99b26250099fc38d30bfaed7797a7275ed3366\n\ parent f87d14a4a236582a0278a916340a793714256864\n\ author Edward Thomson <[email protected]> 1405625055 -0400\n\ committer Rebaser <[email protected]> 1405694510 +0000\n\ gpgsig -----BEGIN PGP SIGNATURE-----\n\ \n\ iQIzBAEBCgAdFiEEgVlDEfSlmKn0fvGgK++h5T2/ctIFAlwZcrAACgkQK++h5T2/\n\ ctIPVhAA42RyZhMdKl5Bm0KtQco2scsukIg2y7tjSwhti91zDu3HQgpusjjo0fQx\n\ ZzB+OrmlvQ9CDcGpZ0THIzXD8GRJoDMPqdrvZVrBWkGcHvw7/YPA8skzsjkauJ8W\n\ 7lzF5LCuHSS6OUmPT/+5hEHPin5PB3zhfszyC+Q7aujnIuPJMrKiMnUa+w1HWifM\n\ km49OOygQ9S6NQoVuEQede22+c76DlDL7yFghGoo1f0sKCE/9LW6SEnwI/bWv9eo\n\ nom5vOPrvQeJiYCQk+2DyWo8RdSxINtY+G9bPE4RXm+6ZgcXECPm9TYDIWpL36fC\n\ jvtGLs98woWFElOziBMp5Tb630GMcSI+q5ivHfJ3WS5NKLYLHBNK4iSFN0/dgAnB\n\ dj6GcKXKWnIBWn6ZM4o40pcM5KSRUUCLtA0ZmjJH4c4zx3X5fUxd+enwkf3e9VZO\n\ fNKC/+xfq6NfoPUPK9+UnchHpJaJw7RG5tZS+sWCz2xpQ1y3/o49xImNyM3wnpvB\n\ cRAZabqIHpZa9/DIUkELOtCzln6niqkjRgg3M/YCCNznwV+0RNgz87VtyTPerdef\n\ xrqn0+ROMF6ebVqIs6PPtuPkxnAJu7TMKXVB5rFnAewS24e6cIGFzeIA7810py3l\n\ cttVRsdOoego+fiy08eFE+aJIeYiINRGhqOBTsuqG4jIdpdKxPE=\n\ =KbsY\n\ -----END PGP SIGNATURE-----\n"; rebase_opts.commit_create_cb = create_cb_signed_gpg; rebase_opts.payload = repo; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_oid__fromstr(&expected_id, "bf78348e45c8286f52b760f1db15cb6da030f2ef", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_s(expected_commit_raw_header, git_commit_raw_header(commit)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_commit_free(commit); git_rebase_free(rebase); } static int create_cb_error( git_oid *out, const git_signature *author, const git_signature *committer, const char *message_encoding, const char *message, const git_tree *tree, size_t parent_count, const git_commit *parents[], void *payload) { GIT_UNUSED(out); GIT_UNUSED(author); GIT_UNUSED(committer); GIT_UNUSED(message_encoding); GIT_UNUSED(message); GIT_UNUSED(tree); GIT_UNUSED(parent_count); GIT_UNUSED(parents); GIT_UNUSED(payload); return GIT_EUSER; } /* git checkout gravy ; git rebase --merge veal */ void test_rebase_sign__create_propagates_error(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_oid commit_id; git_rebase_operation *rebase_operation; git_rebase_options rebase_opts = GIT_REBASE_OPTIONS_INIT; rebase_opts.commit_create_cb = create_cb_error; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_fail_with(GIT_EUSER, git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_rebase_free(rebase); } #ifndef GIT_DEPRECATE_HARD static const char *expected_commit_content = "\ tree cd99b26250099fc38d30bfaed7797a7275ed3366\n\ parent f87d14a4a236582a0278a916340a793714256864\n\ author Edward Thomson <[email protected]> 1405625055 -0400\n\ committer Rebaser <[email protected]> 1405694510 +0000\n\ \n\ Modification 3 to gravy\n"; int signing_cb_passthrough( git_buf *signature, git_buf *signature_field, const char *commit_content, void *payload) { cl_assert_equal_i(0, signature->size); cl_assert_equal_i(0, signature_field->size); cl_assert_equal_s(expected_commit_content, commit_content); cl_assert_equal_p(NULL, payload); return GIT_PASSTHROUGH; } #endif /* !GIT_DEPRECATE_HARD */ /* git checkout gravy ; git rebase --merge veal */ void test_rebase_sign__passthrough_signing_cb(void) { #ifndef GIT_DEPRECATE_HARD git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_id; git_rebase_options rebase_opts = GIT_REBASE_OPTIONS_INIT; git_commit *commit; const char *expected_commit_raw_header = "tree cd99b26250099fc38d30bfaed7797a7275ed3366\n\ parent f87d14a4a236582a0278a916340a793714256864\n\ author Edward Thomson <[email protected]> 1405625055 -0400\n\ committer Rebaser <[email protected]> 1405694510 +0000\n"; rebase_opts.signing_cb = signing_cb_passthrough; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_oid__fromstr(&expected_id, "129183968a65abd6c52da35bff43325001bfc630", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_s(expected_commit_raw_header, git_commit_raw_header(commit)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_commit_free(commit); git_rebase_free(rebase); #endif /* !GIT_DEPRECATE_HARD */ } #ifndef GIT_DEPRECATE_HARD int signing_cb_gpg( git_buf *signature, git_buf *signature_field, const char *commit_content, void *payload) { const char *gpg_signature = "\ -----BEGIN PGP SIGNATURE-----\n\ \n\ iQIzBAEBCgAdFiEEgVlDEfSlmKn0fvGgK++h5T2/ctIFAlwZcrAACgkQK++h5T2/\n\ ctIPVhAA42RyZhMdKl5Bm0KtQco2scsukIg2y7tjSwhti91zDu3HQgpusjjo0fQx\n\ ZzB+OrmlvQ9CDcGpZ0THIzXD8GRJoDMPqdrvZVrBWkGcHvw7/YPA8skzsjkauJ8W\n\ 7lzF5LCuHSS6OUmPT/+5hEHPin5PB3zhfszyC+Q7aujnIuPJMrKiMnUa+w1HWifM\n\ km49OOygQ9S6NQoVuEQede22+c76DlDL7yFghGoo1f0sKCE/9LW6SEnwI/bWv9eo\n\ nom5vOPrvQeJiYCQk+2DyWo8RdSxINtY+G9bPE4RXm+6ZgcXECPm9TYDIWpL36fC\n\ jvtGLs98woWFElOziBMp5Tb630GMcSI+q5ivHfJ3WS5NKLYLHBNK4iSFN0/dgAnB\n\ dj6GcKXKWnIBWn6ZM4o40pcM5KSRUUCLtA0ZmjJH4c4zx3X5fUxd+enwkf3e9VZO\n\ fNKC/+xfq6NfoPUPK9+UnchHpJaJw7RG5tZS+sWCz2xpQ1y3/o49xImNyM3wnpvB\n\ cRAZabqIHpZa9/DIUkELOtCzln6niqkjRgg3M/YCCNznwV+0RNgz87VtyTPerdef\n\ xrqn0+ROMF6ebVqIs6PPtuPkxnAJu7TMKXVB5rFnAewS24e6cIGFzeIA7810py3l\n\ cttVRsdOoego+fiy08eFE+aJIeYiINRGhqOBTsuqG4jIdpdKxPE=\n\ =KbsY\n\ -----END PGP SIGNATURE-----"; cl_assert_equal_i(0, signature->size); cl_assert_equal_i(0, signature_field->size); cl_assert_equal_s(expected_commit_content, commit_content); cl_assert_equal_p(NULL, payload); cl_git_pass(git_buf_set(signature, gpg_signature, strlen(gpg_signature) + 1)); return GIT_OK; } #endif /* !GIT_DEPRECATE_HARD */ /* git checkout gravy ; git rebase --merge veal */ void test_rebase_sign__gpg_with_no_field(void) { #ifndef GIT_DEPRECATE_HARD git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_id; git_rebase_options rebase_opts = GIT_REBASE_OPTIONS_INIT; git_commit *commit; const char *expected_commit_raw_header = "\ tree cd99b26250099fc38d30bfaed7797a7275ed3366\n\ parent f87d14a4a236582a0278a916340a793714256864\n\ author Edward Thomson <[email protected]> 1405625055 -0400\n\ committer Rebaser <[email protected]> 1405694510 +0000\n\ gpgsig -----BEGIN PGP SIGNATURE-----\n\ \n\ iQIzBAEBCgAdFiEEgVlDEfSlmKn0fvGgK++h5T2/ctIFAlwZcrAACgkQK++h5T2/\n\ ctIPVhAA42RyZhMdKl5Bm0KtQco2scsukIg2y7tjSwhti91zDu3HQgpusjjo0fQx\n\ ZzB+OrmlvQ9CDcGpZ0THIzXD8GRJoDMPqdrvZVrBWkGcHvw7/YPA8skzsjkauJ8W\n\ 7lzF5LCuHSS6OUmPT/+5hEHPin5PB3zhfszyC+Q7aujnIuPJMrKiMnUa+w1HWifM\n\ km49OOygQ9S6NQoVuEQede22+c76DlDL7yFghGoo1f0sKCE/9LW6SEnwI/bWv9eo\n\ nom5vOPrvQeJiYCQk+2DyWo8RdSxINtY+G9bPE4RXm+6ZgcXECPm9TYDIWpL36fC\n\ jvtGLs98woWFElOziBMp5Tb630GMcSI+q5ivHfJ3WS5NKLYLHBNK4iSFN0/dgAnB\n\ dj6GcKXKWnIBWn6ZM4o40pcM5KSRUUCLtA0ZmjJH4c4zx3X5fUxd+enwkf3e9VZO\n\ fNKC/+xfq6NfoPUPK9+UnchHpJaJw7RG5tZS+sWCz2xpQ1y3/o49xImNyM3wnpvB\n\ cRAZabqIHpZa9/DIUkELOtCzln6niqkjRgg3M/YCCNznwV+0RNgz87VtyTPerdef\n\ xrqn0+ROMF6ebVqIs6PPtuPkxnAJu7TMKXVB5rFnAewS24e6cIGFzeIA7810py3l\n\ cttVRsdOoego+fiy08eFE+aJIeYiINRGhqOBTsuqG4jIdpdKxPE=\n\ =KbsY\n\ -----END PGP SIGNATURE-----\n"; rebase_opts.signing_cb = signing_cb_gpg; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_oid__fromstr(&expected_id, "bf78348e45c8286f52b760f1db15cb6da030f2ef", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_s(expected_commit_raw_header, git_commit_raw_header(commit)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_commit_free(commit); git_rebase_free(rebase); #endif /* !GIT_DEPRECATE_HARD */ } #ifndef GIT_DEPRECATE_HARD int signing_cb_magic_field( git_buf *signature, git_buf *signature_field, const char *commit_content, void *payload) { const char *signature_content = "magic word: pretty please"; const char *signature_field_content = "magicsig"; cl_assert_equal_p(NULL, signature->ptr); cl_assert_equal_i(0, signature->size); cl_assert_equal_p(NULL, signature_field->ptr); cl_assert_equal_i(0, signature_field->size); cl_assert_equal_s(expected_commit_content, commit_content); cl_assert_equal_p(NULL, payload); cl_git_pass(git_buf_set(signature, signature_content, strlen(signature_content) + 1)); cl_git_pass(git_buf_set(signature_field, signature_field_content, strlen(signature_field_content) + 1)); return GIT_OK; } #endif /* !GIT_DEPRECATE_HARD */ /* git checkout gravy ; git rebase --merge veal */ void test_rebase_sign__custom_signature_field(void) { #ifndef GIT_DEPRECATE_HARD git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_id; git_rebase_options rebase_opts = GIT_REBASE_OPTIONS_INIT; git_commit *commit; const char *expected_commit_raw_header = "\ tree cd99b26250099fc38d30bfaed7797a7275ed3366\n\ parent f87d14a4a236582a0278a916340a793714256864\n\ author Edward Thomson <[email protected]> 1405625055 -0400\n\ committer Rebaser <[email protected]> 1405694510 +0000\n\ magicsig magic word: pretty please\n"; rebase_opts.signing_cb = signing_cb_magic_field; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_oid__fromstr(&expected_id, "f46a4a8d26ae411b02aa61b7d69576627f4a1e1c", GIT_OID_SHA1); cl_assert_equal_oid(&expected_id, &commit_id); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_s(expected_commit_raw_header, git_commit_raw_header(commit)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_commit_free(commit); git_rebase_free(rebase); #endif /* !GIT_DEPRECATE_HARD */ }
libgit2-main
tests/libgit2/rebase/sign.c
#include "clar_libgit2.h" #include "git2/rebase.h" #include "posix.h" #include <fcntl.h> static git_repository *repo; static git_index *_index; static git_signature *signature; /* Fixture setup and teardown */ void test_rebase_setup__initialize(void) { repo = cl_git_sandbox_init("rebase"); cl_git_pass(git_repository_index(&_index, repo)); cl_git_pass(git_signature_now(&signature, "Rebaser", "[email protected]")); } void test_rebase_setup__cleanup(void) { git_signature_free(signature); git_index_free(_index); cl_git_sandbox_cleanup(); } /* git checkout beef ; git rebase --merge master * git checkout beef ; git rebase --merge master */ void test_rebase_setup__blocked_when_in_progress(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); git_rebase_free(rebase); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_git_fail(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); } /* git checkout beef ; git rebase --merge master */ void test_rebase_setup__merge(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_reference *head; git_commit *head_commit; git_oid head_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_file("da9c51a23d02d931a486f45ad18cda05cf5d2b94\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("8d1f13f93c4995760ac07d129246ac1ff64c0be9\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("3069cc907e6294623e5917ef6de663928c1febfb\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("588e5d2f04d49707fe4aab865e1deacaf7ef6787\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } /* git checkout beef && git rebase --merge --root --onto master */ void test_rebase_setup__merge_root(void) { git_rebase *rebase; git_reference *branch_ref, *onto_ref; git_annotated_commit *branch_head, *onto_head; git_reference *head; git_commit *head_commit; git_oid head_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&onto_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&onto_head, repo, onto_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, NULL, onto_head, NULL)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_assert_equal_file("da9c51a23d02d931a486f45ad18cda05cf5d2b94\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("8d1f13f93c4995760ac07d129246ac1ff64c0be9\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("3069cc907e6294623e5917ef6de663928c1febfb\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("588e5d2f04d49707fe4aab865e1deacaf7ef6787\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_reference_free(branch_ref); git_reference_free(onto_ref); git_rebase_free(rebase); } /* git checkout gravy && git rebase --merge --onto master veal */ void test_rebase_setup__merge_onto_and_upstream(void) { git_rebase *rebase; git_reference *branch1_ref, *branch2_ref, *onto_ref; git_annotated_commit *branch1_head, *branch2_head, *onto_head; git_reference *head; git_commit *head_commit; git_oid head_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch1_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&branch2_ref, repo, "refs/heads/veal")); cl_git_pass(git_reference_lookup(&onto_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch1_head, repo, branch1_ref)); cl_git_pass(git_annotated_commit_from_ref(&branch2_head, repo, branch2_ref)); cl_git_pass(git_annotated_commit_from_ref(&onto_head, repo, onto_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch1_head, branch2_head, onto_head, NULL)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("d616d97082eb7bb2dc6f180a7cca940993b7a56f\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_assert_equal_file("d616d97082eb7bb2dc6f180a7cca940993b7a56f\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("1\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("d616d97082eb7bb2dc6f180a7cca940993b7a56f\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch1_head); git_annotated_commit_free(branch2_head); git_annotated_commit_free(onto_head); git_reference_free(branch1_ref); git_reference_free(branch2_ref); git_reference_free(onto_ref); git_rebase_free(rebase); } /* git checkout beef && git rebase --merge --onto master gravy veal */ void test_rebase_setup__merge_onto_upstream_and_branch(void) { git_rebase *rebase; git_reference *upstream_ref, *branch_ref, *onto_ref; git_annotated_commit *upstream_head, *branch_head, *onto_head; git_reference *head; git_commit *head_commit; git_oid head_id; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_repository_set_head(repo, "refs/heads/beef")); cl_git_pass(git_checkout_head(repo, &checkout_opts)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/veal")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&onto_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_annotated_commit_from_ref(&onto_head, repo, onto_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, onto_head, NULL)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("f87d14a4a236582a0278a916340a793714256864\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_assert_equal_file("3e8989b5a16d5258c935d998ef0e6bb139cc4757\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("4cacc6f6e740a5bc64faa33e04b8ef0733d8a127\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("f87d14a4a236582a0278a916340a793714256864\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("3\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("f87d14a4a236582a0278a916340a793714256864\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(upstream_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_reference_free(upstream_ref); git_reference_free(branch_ref); git_reference_free(onto_ref); git_rebase_free(rebase); } /* git checkout beef && git rebase --merge --onto `git rev-parse master` * `git rev-parse veal` `git rev-parse gravy` */ void test_rebase_setup__merge_onto_upstream_and_branch_by_id(void) { git_rebase *rebase; git_oid upstream_id, branch_id, onto_id; git_annotated_commit *upstream_head, *branch_head, *onto_head; git_reference *head; git_commit *head_commit; git_oid head_id; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_repository_set_head(repo, "refs/heads/beef")); cl_git_pass(git_checkout_head(repo, &checkout_opts)); cl_git_pass(git_oid__fromstr(&upstream_id, "f87d14a4a236582a0278a916340a793714256864", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&branch_id, "d616d97082eb7bb2dc6f180a7cca940993b7a56f", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&onto_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_lookup(&upstream_head, repo, &upstream_id)); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_lookup(&onto_head, repo, &onto_id)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, onto_head, NULL)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("d616d97082eb7bb2dc6f180a7cca940993b7a56f\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); cl_assert_equal_file("d616d97082eb7bb2dc6f180a7cca940993b7a56f\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("1\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("d616d97082eb7bb2dc6f180a7cca940993b7a56f\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(upstream_head); git_annotated_commit_free(branch_head); git_annotated_commit_free(onto_head); git_rebase_free(rebase); } /* Ensure merge commits are dropped in a rebase */ /* git checkout veal && git rebase --merge master */ void test_rebase_setup__branch_with_merges(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_reference *head; git_commit *head_commit; git_oid head_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/veal")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("f87d14a4a236582a0278a916340a793714256864\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_file("4bed71df7017283cac61bbf726197ad6a5a18b84\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("2aa3ce842094e08ebac152b3d6d5b0fff39f9c6e\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("3e8989b5a16d5258c935d998ef0e6bb139cc4757\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("4cacc6f6e740a5bc64faa33e04b8ef0733d8a127\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("f87d14a4a236582a0278a916340a793714256864\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("f87d14a4a236582a0278a916340a793714256864\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } /* git checkout barley && git rebase --merge master */ void test_rebase_setup__orphan_branch(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_reference *head; git_commit *head_commit; git_oid head_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/barley")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("12c084412b952396962eb420716df01022b847cc\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_file("aa4c42aecdfc7cd989bbc3209934ea7cda3f4d88\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("e4f809f826c1a9fc929874bc0e4644dd2f2a1af4\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("9539b2cc291d6a6b1b266df8474d31fdd344dd79\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("013cc32d341bab0e6f039f50f153c18986f16c58\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("12c084412b952396962eb420716df01022b847cc\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("12c084412b952396962eb420716df01022b847cc\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } /* git checkout beef && git rebase --merge master */ void test_rebase_setup__merge_null_branch_uses_HEAD(void) { git_rebase *rebase; git_reference *upstream_ref; git_annotated_commit *upstream_head; git_reference *head; git_commit *head_commit; git_oid head_id; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_repository_set_head(repo, "refs/heads/beef")); cl_git_pass(git_checkout_head(repo, &checkout_opts)); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, NULL, upstream_head, NULL, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_file("da9c51a23d02d931a486f45ad18cda05cf5d2b94\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("8d1f13f93c4995760ac07d129246ac1ff64c0be9\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("3069cc907e6294623e5917ef6de663928c1febfb\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("588e5d2f04d49707fe4aab865e1deacaf7ef6787\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(upstream_head); git_reference_free(upstream_ref); git_rebase_free(rebase); } /* git checkout b146bd7608eac53d9bf9e1a6963543588b555c64 && git rebase --merge master */ void test_rebase_setup__merge_from_detached(void) { git_rebase *rebase; git_reference *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_reference *head; git_commit *head_commit; git_oid branch_id, head_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_oid__fromstr(&branch_id, "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_file("da9c51a23d02d931a486f45ad18cda05cf5d2b94\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("8d1f13f93c4995760ac07d129246ac1ff64c0be9\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("3069cc907e6294623e5917ef6de663928c1febfb\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("588e5d2f04d49707fe4aab865e1deacaf7ef6787\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("master\n", 7, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(upstream_ref); git_rebase_free(rebase); } /* git checkout beef && git rebase --merge efad0b11c47cb2f0220cbd6f5b0f93bb99064b00 */ void test_rebase_setup__merge_branch_by_id(void) { git_rebase *rebase; git_reference *branch_ref; git_annotated_commit *branch_head, *upstream_head; git_reference *head; git_commit *head_commit; git_oid head_id, upstream_id; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_oid__fromstr(&upstream_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_lookup(&upstream_head, repo, &upstream_id)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_assert_equal_i(GIT_REPOSITORY_STATE_REBASE_MERGE, git_repository_state(repo)); git_oid__fromstr(&head_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head, GIT_OBJECT_COMMIT)); cl_assert_equal_oid(&head_id, git_commit_id(head_commit)); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/ORIG_HEAD"); cl_assert_equal_file("da9c51a23d02d931a486f45ad18cda05cf5d2b94\n", 41, "rebase/.git/rebase-merge/cmt.1"); cl_assert_equal_file("8d1f13f93c4995760ac07d129246ac1ff64c0be9\n", 41, "rebase/.git/rebase-merge/cmt.2"); cl_assert_equal_file("3069cc907e6294623e5917ef6de663928c1febfb\n", 41, "rebase/.git/rebase-merge/cmt.3"); cl_assert_equal_file("588e5d2f04d49707fe4aab865e1deacaf7ef6787\n", 41, "rebase/.git/rebase-merge/cmt.4"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/cmt.5"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto"); cl_assert_equal_file("efad0b11c47cb2f0220cbd6f5b0f93bb99064b00\n", 41, "rebase/.git/rebase-merge/onto_name"); cl_assert_equal_file("b146bd7608eac53d9bf9e1a6963543588b555c64\n", 41, "rebase/.git/rebase-merge/orig-head"); git_commit_free(head_commit); git_reference_free(head); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_rebase_free(rebase); } static int rebase_is_blocked(void) { git_rebase *rebase = NULL; int error; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); error = git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); return error; } void test_rebase_setup__blocked_for_staged_change(void) { cl_git_rewritefile("rebase/newfile.txt", "Stage an add"); git_index_add_bypath(_index, "newfile.txt"); cl_git_fail(rebase_is_blocked()); } void test_rebase_setup__blocked_for_unstaged_change(void) { cl_git_rewritefile("rebase/asparagus.txt", "Unstaged change"); cl_git_fail(rebase_is_blocked()); } void test_rebase_setup__not_blocked_for_untracked_add(void) { cl_git_rewritefile("rebase/newfile.txt", "Untracked file"); cl_git_pass(rebase_is_blocked()); }
libgit2-main
tests/libgit2/rebase/setup.c
#include "clar_libgit2.h" #include "git2/checkout.h" #include "git2/rebase.h" #include "posix.h" #include "signature.h" #include "../submodule/submodule_helpers.h" #include <fcntl.h> static git_repository *repo; static git_signature *signature; /* Fixture setup and teardown */ void test_rebase_submodule__initialize(void) { git_index *index; git_oid tree_oid, commit_id; git_tree *tree; git_commit *parent; git_object *obj; git_reference *master_ref; git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; opts.checkout_strategy = GIT_CHECKOUT_FORCE; repo = cl_git_sandbox_init("rebase-submodule"); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1405694510, 0)); rewrite_gitmodules(git_repository_workdir(repo)); cl_git_pass(git_submodule_set_url(repo, "my-submodule", git_repository_path(repo))); /* We have to commit the rewritten .gitmodules file */ cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_add_bypath(index, ".gitmodules")); cl_git_pass(git_index_write(index)); cl_git_pass(git_index_write_tree(&tree_oid, index)); cl_git_pass(git_tree_lookup(&tree, repo, &tree_oid)); cl_git_pass(git_repository_head(&master_ref, repo)); cl_git_pass(git_commit_lookup(&parent, repo, git_reference_target(master_ref))); cl_git_pass(git_commit_create_v(&commit_id, repo, git_reference_name(master_ref), signature, signature, NULL, "Fixup .gitmodules", tree, 1, parent)); /* And a final reset, for good measure */ cl_git_pass(git_object_lookup(&obj, repo, &commit_id, GIT_OBJECT_COMMIT)); cl_git_pass(git_reset(repo, obj, GIT_RESET_HARD, &opts)); git_index_free(index); git_object_free(obj); git_commit_free(parent); git_reference_free(master_ref); git_tree_free(tree); } void test_rebase_submodule__cleanup(void) { git_signature_free(signature); cl_git_sandbox_cleanup(); } void test_rebase_submodule__init_untracked(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_str untracked_path = GIT_STR_INIT; FILE *fp; git_submodule *submodule; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/asparagus")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_submodule_lookup(&submodule, repo, "my-submodule")); cl_git_pass(git_submodule_update(submodule, 1, NULL)); git_str_printf(&untracked_path, "%s/my-submodule/untracked", git_repository_workdir(repo)); fp = fopen(git_str_cstr(&untracked_path), "w"); fprintf(fp, "An untracked file in a submodule should not block a rebase\n"); fclose(fp); git_str_dispose(&untracked_path); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); git_submodule_free(submodule); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); }
libgit2-main
tests/libgit2/rebase/submodule.c
#include "clar_libgit2.h" #include "git2/checkout.h" #include "git2/rebase.h" #include "posix.h" #include "signature.h" #include <fcntl.h> static git_repository *repo; static git_signature *signature; static void set_core_autocrlf_to(git_repository *repo, bool value) { git_config *cfg; cl_git_pass(git_repository_config(&cfg, repo)); cl_git_pass(git_config_set_bool(cfg, "core.autocrlf", value)); git_config_free(cfg); } /* Fixture setup and teardown */ void test_rebase_merge__initialize(void) { repo = cl_git_sandbox_init("rebase"); cl_git_pass(git_signature_new(&signature, "Rebaser", "[email protected]", 1405694510, 0)); set_core_autocrlf_to(repo, false); } void test_rebase_merge__cleanup(void) { git_signature_free(signature); cl_git_sandbox_cleanup(); } void test_rebase_merge__next(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_status_list *status_list; const git_status_entry *status_entry; git_oid pick_id, file1_id; git_oid master_id, beef_id; git_oid__fromstr(&master_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); git_oid__fromstr(&beef_id, "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_assert_equal_s("refs/heads/beef", git_rebase_orig_head_name(rebase)); cl_assert_equal_oid(&beef_id, git_rebase_orig_head_id(rebase)); cl_assert_equal_s("master", git_rebase_onto_name(rebase)); cl_assert_equal_oid(&master_id, git_rebase_onto_id(rebase)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); git_oid__fromstr(&pick_id, "da9c51a23d02d931a486f45ad18cda05cf5d2b94", GIT_OID_SHA1); cl_assert_equal_i(GIT_REBASE_OPERATION_PICK, rebase_operation->type); cl_assert_equal_oid(&pick_id, &rebase_operation->id); cl_assert_equal_file("da9c51a23d02d931a486f45ad18cda05cf5d2b94\n", 41, "rebase/.git/rebase-merge/current"); cl_assert_equal_file("1\n", 2, "rebase/.git/rebase-merge/msgnum"); cl_git_pass(git_status_list_new(&status_list, repo, NULL)); cl_assert_equal_i(1, git_status_list_entrycount(status_list)); cl_assert(status_entry = git_status_byindex(status_list, 0)); cl_assert_equal_s("beef.txt", status_entry->head_to_index->new_file.path); git_oid__fromstr(&file1_id, "8d95ea62e621f1d38d230d9e7d206e41096d76af", GIT_OID_SHA1); cl_assert_equal_oid(&file1_id, &status_entry->head_to_index->new_file.id); git_status_list_free(status_list); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__next_with_conflicts(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_status_list *status_list; const git_status_entry *status_entry; git_oid pick_id, commit_id; const char *expected_merge = "ASPARAGUS SOUP.\n" "\n" "<<<<<<< master\n" "TAKE FOUR LARGE BUNCHES of asparagus, scrape it nicely, cut off one inch\n" "OF THE TOPS, and lay them in water, chop the stalks and put them on the\n" "FIRE WITH A PIECE OF BACON, a large onion cut up, and pepper and salt;\n" "ADD TWO QUARTS OF WATER, boil them till the stalks are quite soft, then\n" "PULP THEM THROUGH A SIEVE, and strain the water to it, which must be put\n" "=======\n" "Take four large bunches of asparagus, scrape it nicely, CUT OFF ONE INCH\n" "of the tops, and lay them in water, chop the stalks and PUT THEM ON THE\n" "fire with a piece of bacon, a large onion cut up, and pepper and salt;\n" "add two quarts of water, boil them till the stalks are quite soft, then\n" "pulp them through a sieve, and strain the water to it, which must be put\n" ">>>>>>> Conflicting modification 1 to asparagus\n" "back in the pot; put into it a chicken cut up, with the tops of\n" "asparagus which had been laid by, boil it until these last articles are\n" "sufficiently done, thicken with flour, butter and milk, and serve it up.\n"; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/asparagus")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); git_oid__fromstr(&pick_id, "33f915f9e4dbd9f4b24430e48731a59b45b15500", GIT_OID_SHA1); cl_assert_equal_i(GIT_REBASE_OPERATION_PICK, rebase_operation->type); cl_assert_equal_oid(&pick_id, &rebase_operation->id); cl_assert_equal_file("33f915f9e4dbd9f4b24430e48731a59b45b15500\n", 41, "rebase/.git/rebase-merge/current"); cl_assert_equal_file("1\n", 2, "rebase/.git/rebase-merge/msgnum"); cl_git_pass(git_status_list_new(&status_list, repo, NULL)); cl_assert_equal_i(1, git_status_list_entrycount(status_list)); cl_assert(status_entry = git_status_byindex(status_list, 0)); cl_assert_equal_s("asparagus.txt", status_entry->head_to_index->new_file.path); cl_assert_equal_file(expected_merge, strlen(expected_merge), "rebase/asparagus.txt"); cl_git_fail_with(GIT_EUNMERGED, git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_status_list_free(status_list); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__next_stops_with_iterover(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; int error; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_fail(error = git_rebase_next(&rebase_operation, rebase)); cl_assert_equal_i(GIT_ITEROVER, error); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/end"); cl_assert_equal_file("5\n", 2, "rebase/.git/rebase-merge/msgnum"); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__commit(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, tree_id, parent_id; git_signature *author; git_commit *commit; git_reflog *reflog; const git_reflog_entry *reflog_entry; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); git_oid__fromstr(&parent_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_assert_equal_i(1, git_commit_parentcount(commit)); cl_assert_equal_oid(&parent_id, git_commit_parent_id(commit, 0)); git_oid__fromstr(&tree_id, "4461379789c777d2a6c1f2ee0e9d6c86731b9992", GIT_OID_SHA1); cl_assert_equal_oid(&tree_id, git_commit_tree_id(commit)); cl_assert_equal_s(NULL, git_commit_message_encoding(commit)); cl_assert_equal_s("Modification 1 to beef\n", git_commit_message(commit)); cl_git_pass(git_signature_new(&author, "Edward Thomson", "[email protected]", 1405621769, 0-(4*60))); cl_assert(git_signature__equal(author, git_commit_author(commit))); cl_assert(git_signature__equal(signature, git_commit_committer(commit))); /* Make sure the reflogs are updated appropriately */ cl_git_pass(git_reflog_read(&reflog, repo, "HEAD")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(&parent_id, git_reflog_entry_id_old(reflog_entry)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_new(reflog_entry)); cl_assert_equal_s("rebase: Modification 1 to beef", git_reflog_entry_message(reflog_entry)); git_reflog_free(reflog); git_signature_free(author); git_commit_free(commit); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__commit_with_id(void) { git_rebase *rebase; git_oid branch_id, upstream_id; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, tree_id, parent_id; git_signature *author; git_commit *commit; git_reflog *reflog; const git_reflog_entry *reflog_entry; cl_git_pass(git_oid__fromstr(&branch_id, "b146bd7608eac53d9bf9e1a6963543588b555c64", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&upstream_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_lookup(&upstream_head, repo, &upstream_id)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); git_oid__fromstr(&parent_id, "efad0b11c47cb2f0220cbd6f5b0f93bb99064b00", GIT_OID_SHA1); cl_assert_equal_i(1, git_commit_parentcount(commit)); cl_assert_equal_oid(&parent_id, git_commit_parent_id(commit, 0)); git_oid__fromstr(&tree_id, "4461379789c777d2a6c1f2ee0e9d6c86731b9992", GIT_OID_SHA1); cl_assert_equal_oid(&tree_id, git_commit_tree_id(commit)); cl_assert_equal_s(NULL, git_commit_message_encoding(commit)); cl_assert_equal_s("Modification 1 to beef\n", git_commit_message(commit)); cl_git_pass(git_signature_new(&author, "Edward Thomson", "[email protected]", 1405621769, 0-(4*60))); cl_assert(git_signature__equal(author, git_commit_author(commit))); cl_assert(git_signature__equal(signature, git_commit_committer(commit))); /* Make sure the reflogs are updated appropriately */ cl_git_pass(git_reflog_read(&reflog, repo, "HEAD")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(&parent_id, git_reflog_entry_id_old(reflog_entry)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_new(reflog_entry)); cl_assert_equal_s("rebase: Modification 1 to beef", git_reflog_entry_message(reflog_entry)); git_reflog_free(reflog); git_signature_free(author); git_commit_free(commit); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_rebase_free(rebase); } void test_rebase_merge__blocked_when_dirty(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); /* Allow untracked files */ cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_mkfile("rebase/untracked_file.txt", "This is untracked\n"); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); /* Do not allow unstaged */ cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_mkfile("rebase/veal.txt", "This is an unstaged change\n"); cl_git_fail_with(GIT_EUNMERGED, git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__commit_updates_rewritten(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_assert_equal_file( "da9c51a23d02d931a486f45ad18cda05cf5d2b94 776e4c48922799f903f03f5f6e51da8b01e4cce0\n" "8d1f13f93c4995760ac07d129246ac1ff64c0be9 ba1f9b4fd5cf8151f7818be2111cc0869f1eb95a\n", 164, "rebase/.git/rebase-merge/rewritten"); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__commit_drops_already_applied(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; int error; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/green_pea")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_fail(error = git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_assert_equal_i(GIT_EAPPLIED, error); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_assert_equal_file( "8d1f13f93c4995760ac07d129246ac1ff64c0be9 2ac4fb7b74c1287f6c792acad759e1ec01e18dae\n", 82, "rebase/.git/rebase-merge/rewritten"); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__finish(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref, *head_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; git_reflog *reflog; const git_reflog_entry *reflog_entry; int error; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_fail(error = git_rebase_next(&rebase_operation, rebase)); cl_assert_equal_i(GIT_ITEROVER, error); cl_git_pass(git_rebase_finish(rebase, signature)); cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&head_ref, repo, "HEAD")); cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head_ref)); cl_assert_equal_s("refs/heads/gravy", git_reference_symbolic_target(head_ref)); /* Make sure the reflogs are updated appropriately */ cl_git_pass(git_reflog_read(&reflog, repo, "HEAD")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_old(reflog_entry)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_new(reflog_entry)); cl_assert_equal_s("rebase finished: returning to refs/heads/gravy", git_reflog_entry_message(reflog_entry)); git_reflog_free(reflog); cl_git_pass(git_reflog_read(&reflog, repo, "refs/heads/gravy")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(git_annotated_commit_id(branch_head), git_reflog_entry_id_old(reflog_entry)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_new(reflog_entry)); cl_assert_equal_s("rebase finished: refs/heads/gravy onto f87d14a4a236582a0278a916340a793714256864", git_reflog_entry_message(reflog_entry)); git_reflog_free(reflog); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(head_ref); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__detached_finish(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref, *head_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; git_reflog *reflog; const git_reflog_entry *reflog_entry; git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; int error; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_repository_set_head_detached_from_annotated(repo, branch_head)); opts.checkout_strategy = GIT_CHECKOUT_FORCE; git_checkout_head(repo, &opts); cl_git_pass(git_rebase_init(&rebase, repo, NULL, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_fail(error = git_rebase_next(&rebase_operation, rebase)); cl_assert_equal_i(GIT_ITEROVER, error); cl_git_pass(git_rebase_finish(rebase, signature)); cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&head_ref, repo, "HEAD")); cl_assert_equal_i(GIT_REFERENCE_DIRECT, git_reference_type(head_ref)); /* Make sure the reflogs are updated appropriately */ cl_git_pass(git_reflog_read(&reflog, repo, "HEAD")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(git_annotated_commit_id(upstream_head), git_reflog_entry_id_old(reflog_entry)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_new(reflog_entry)); git_reflog_free(reflog); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(head_ref); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__finish_with_ids(void) { git_rebase *rebase; git_reference *head_ref; git_oid branch_id, upstream_id; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id; git_reflog *reflog; const git_reflog_entry *reflog_entry; int error; cl_git_pass(git_oid__fromstr(&branch_id, "d616d97082eb7bb2dc6f180a7cca940993b7a56f", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&upstream_id, "f87d14a4a236582a0278a916340a793714256864", GIT_OID_SHA1)); cl_git_pass(git_annotated_commit_lookup(&branch_head, repo, &branch_id)); cl_git_pass(git_annotated_commit_lookup(&upstream_head, repo, &upstream_id)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_fail(error = git_rebase_next(&rebase_operation, rebase)); cl_assert_equal_i(GIT_ITEROVER, error); cl_git_pass(git_rebase_finish(rebase, signature)); cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); cl_git_pass(git_reference_lookup(&head_ref, repo, "HEAD")); cl_assert_equal_i(GIT_REFERENCE_DIRECT, git_reference_type(head_ref)); cl_assert_equal_oid(&commit_id, git_reference_target(head_ref)); /* reflogs are not updated as if we were operating on proper * branches. check that the last reflog entry is the rebase. */ cl_git_pass(git_reflog_read(&reflog, repo, "HEAD")); cl_assert(reflog_entry = git_reflog_entry_byindex(reflog, 0)); cl_assert_equal_oid(&commit_id, git_reflog_entry_id_new(reflog_entry)); cl_assert_equal_s("rebase: Modification 3 to gravy", git_reflog_entry_message(reflog_entry)); git_reflog_free(reflog); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(head_ref); git_rebase_free(rebase); } void test_rebase_merge__no_common_ancestor(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, expected_final_id; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/barley")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_finish(rebase, signature)); git_oid__fromstr(&expected_final_id, "71e7ee8d4fe7d8bf0d107355197e0a953dfdb7f3", GIT_OID_SHA1); cl_assert_equal_oid(&expected_final_id, &commit_id); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } static void test_copy_note( const git_rebase_options *opts, bool should_exist) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_commit *branch_commit; git_rebase_operation *rebase_operation; git_oid note_id, commit_id; git_note *note = NULL; int error; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_reference_peel((git_object **)&branch_commit, branch_ref, GIT_OBJECT_COMMIT)); /* Add a note to a commit */ cl_git_pass(git_note_create(&note_id, repo, "refs/notes/test", git_commit_author(branch_commit), git_commit_committer(branch_commit), git_commit_id(branch_commit), "This is a commit note.", 0)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, opts)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_finish(rebase, signature)); cl_assert_equal_i(GIT_REPOSITORY_STATE_NONE, git_repository_state(repo)); if (should_exist) { cl_git_pass(git_note_read(&note, repo, "refs/notes/test", &commit_id)); cl_assert_equal_s("This is a commit note.", git_note_message(note)); } else { cl_git_fail(error = git_note_read(&note, repo, "refs/notes/test", &commit_id)); cl_assert_equal_i(GIT_ENOTFOUND, error); } git_note_free(note); git_commit_free(branch_commit); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__copy_notes_off_by_default(void) { test_copy_note(NULL, 0); } void test_rebase_merge__copy_notes_specified_in_options(void) { git_rebase_options opts = GIT_REBASE_OPTIONS_INIT; opts.rewrite_notes_ref = "refs/notes/test"; test_copy_note(&opts, 1); } void test_rebase_merge__copy_notes_specified_in_config(void) { git_config *config; cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_string(config, "notes.rewriteRef", "refs/notes/test")); test_copy_note(NULL, 1); } void test_rebase_merge__copy_notes_disabled_in_config(void) { git_config *config; cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_bool(config, "notes.rewrite.rebase", 0)); cl_git_pass(git_config_set_string(config, "notes.rewriteRef", "refs/notes/test")); test_copy_note(NULL, 0); } static void rebase_checkout_progress_cb( const char *path, size_t completed_steps, size_t total_steps, void *payload) { int *called = payload; GIT_UNUSED(path); GIT_UNUSED(completed_steps); GIT_UNUSED(total_steps); *called = 1; } void test_rebase_merge__custom_checkout_options(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_options rebase_options = GIT_REBASE_OPTIONS_INIT; git_checkout_options checkout_options = GIT_CHECKOUT_OPTIONS_INIT; git_rebase_operation *rebase_operation; int called = 0; checkout_options.progress_cb = rebase_checkout_progress_cb; checkout_options.progress_payload = &called; memcpy(&rebase_options.checkout_options, &checkout_options, sizeof(git_checkout_options)); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/beef")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); called = 0; cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_options)); cl_assert_equal_i(1, called); called = 0; cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_assert_equal_i(1, called); called = 0; cl_git_pass(git_rebase_abort(rebase)); cl_assert_equal_i(1, called); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__custom_merge_options(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_options rebase_options = GIT_REBASE_OPTIONS_INIT; git_rebase_operation *rebase_operation; rebase_options.merge_options.flags |= GIT_MERGE_FAIL_ON_CONFLICT | GIT_MERGE_SKIP_REUC; cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/asparagus")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/master")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, &rebase_options)); cl_git_fail_with(GIT_EMERGECONFLICT, git_rebase_next(&rebase_operation, rebase)); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); } void test_rebase_merge__with_directories(void) { git_rebase *rebase; git_reference *branch_ref, *upstream_ref; git_annotated_commit *branch_head, *upstream_head; git_rebase_operation *rebase_operation; git_oid commit_id, tree_id; git_commit *commit; git_oid__fromstr(&tree_id, "a4d6d9c3d57308fd8e320cf2525bae8f1adafa57", GIT_OID_SHA1); cl_git_pass(git_reference_lookup(&branch_ref, repo, "refs/heads/deep_gravy")); cl_git_pass(git_reference_lookup(&upstream_ref, repo, "refs/heads/veal")); cl_git_pass(git_annotated_commit_from_ref(&branch_head, repo, branch_ref)); cl_git_pass(git_annotated_commit_from_ref(&upstream_head, repo, upstream_ref)); cl_git_pass(git_rebase_init(&rebase, repo, branch_head, upstream_head, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_pass(git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_rebase_commit(&commit_id, rebase, NULL, signature, NULL, NULL)); cl_git_fail_with(GIT_ITEROVER, git_rebase_next(&rebase_operation, rebase)); cl_git_pass(git_commit_lookup(&commit, repo, &commit_id)); cl_assert_equal_oid(&tree_id, git_commit_tree_id(commit)); git_commit_free(commit); git_annotated_commit_free(branch_head); git_annotated_commit_free(upstream_head); git_reference_free(branch_ref); git_reference_free(upstream_ref); git_rebase_free(rebase); }
libgit2-main
tests/libgit2/rebase/merge.c
#include "clar_libgit2.h" #include "repo/repo_helpers.h" void test_repo_getters__is_empty_correctly_deals_with_pristine_looking_repos(void) { git_repository *repo; repo = cl_git_sandbox_init("empty_bare.git"); cl_git_remove_placeholders(git_repository_path(repo), "dummy-marker.txt"); cl_assert_equal_i(true, git_repository_is_empty(repo)); cl_git_sandbox_cleanup(); } void test_repo_getters__is_empty_can_detect_used_repositories(void) { git_repository *repo; cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git"))); cl_assert_equal_i(false, git_repository_is_empty(repo)); git_repository_free(repo); } void test_repo_getters__is_empty_can_detect_repositories_with_defaultbranch_config_empty(void) { git_repository *repo; create_tmp_global_config("tmp_global_path", "init.defaultBranch", ""); cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git"))); cl_assert_equal_i(false, git_repository_is_empty(repo)); git_repository_free(repo); } void test_repo_getters__retrieving_the_odb_honors_the_refcount(void) { git_odb *odb; git_repository *repo; cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git"))); cl_git_pass(git_repository_odb(&odb, repo)); cl_assert(((git_refcount *)odb)->refcount.val == 2); git_repository_free(repo); cl_assert(((git_refcount *)odb)->refcount.val == 1); git_odb_free(odb); }
libgit2-main
tests/libgit2/repo/getters.c
#include "clar_libgit2.h" #include "git2/sys/repository.h" #include "odb.h" #include "posix.h" #include "util.h" #include "path.h" #include "futils.h" static git_repository *repo; void test_repo_setters__initialize(void) { cl_fixture_sandbox("testrepo.git"); cl_git_pass(git_repository_open(&repo, "testrepo.git")); cl_must_pass(p_mkdir("new_workdir", 0777)); } void test_repo_setters__cleanup(void) { git_repository_free(repo); repo = NULL; cl_fixture_cleanup("testrepo.git"); cl_fixture_cleanup("new_workdir"); } void test_repo_setters__setting_a_workdir_turns_a_bare_repository_into_a_standard_one(void) { cl_assert(git_repository_is_bare(repo) == 1); cl_assert(git_repository_workdir(repo) == NULL); cl_git_pass(git_repository_set_workdir(repo, "./new_workdir", false)); cl_assert(git_repository_workdir(repo) != NULL); cl_assert(git_repository_is_bare(repo) == 0); } void test_repo_setters__setting_a_workdir_prettifies_its_path(void) { cl_git_pass(git_repository_set_workdir(repo, "./new_workdir", false)); cl_assert(git__suffixcmp(git_repository_workdir(repo), "new_workdir/") == 0); } void test_repo_setters__setting_a_workdir_creates_a_gitlink(void) { git_config *cfg; git_buf buf = GIT_BUF_INIT; git_str content = GIT_STR_INIT; cl_git_pass(git_repository_set_workdir(repo, "./new_workdir", true)); cl_assert(git_fs_path_isfile("./new_workdir/.git")); cl_git_pass(git_futils_readbuffer(&content, "./new_workdir/.git")); cl_assert(git__prefixcmp(git_str_cstr(&content), "gitdir: ") == 0); cl_assert(git__suffixcmp(git_str_cstr(&content), "testrepo.git/") == 0); git_str_dispose(&content); cl_git_pass(git_repository_config(&cfg, repo)); cl_git_pass(git_config_get_string_buf(&buf, cfg, "core.worktree")); cl_assert(git__suffixcmp(buf.ptr, "new_workdir/") == 0); git_buf_dispose(&buf); git_config_free(cfg); } void test_repo_setters__setting_a_new_index_on_a_repo_which_has_already_loaded_one_properly_honors_the_refcount(void) { git_index *new_index; cl_git_pass(git_index_open(&new_index, "./my-index")); cl_assert(((git_refcount *)new_index)->refcount.val == 1); git_repository_set_index(repo, new_index); cl_assert(((git_refcount *)new_index)->refcount.val == 2); git_repository_free(repo); cl_assert(((git_refcount *)new_index)->refcount.val == 1); git_index_free(new_index); /* * Ensure the cleanup method won't try to free the repo as it's already been taken care of */ repo = NULL; } void test_repo_setters__setting_a_new_odb_on_a_repo_which_already_loaded_one_properly_honors_the_refcount(void) { git_odb *new_odb; cl_git_pass(git_odb__open(&new_odb, "./testrepo.git/objects", NULL)); cl_assert(((git_refcount *)new_odb)->refcount.val == 1); git_repository_set_odb(repo, new_odb); cl_assert(((git_refcount *)new_odb)->refcount.val == 2); git_repository_free(repo); cl_assert(((git_refcount *)new_odb)->refcount.val == 1); git_odb_free(new_odb); /* * Ensure the cleanup method won't try to free the repo as it's already been taken care of */ repo = NULL; }
libgit2-main
tests/libgit2/repo/setters.c
#include "clar_libgit2.h" #include "refs.h" #include "posix.h" #include "futils.h" static git_repository *_repo; static git_str _path; void test_repo_state__initialize(void) { _repo = cl_git_sandbox_init("testrepo.git"); } void test_repo_state__cleanup(void) { cl_git_sandbox_cleanup(); git_str_dispose(&_path); } static void setup_simple_state(const char *filename) { cl_git_pass(git_str_joinpath(&_path, git_repository_path(_repo), filename)); git_futils_mkpath2file(git_str_cstr(&_path), 0777); cl_git_mkfile(git_str_cstr(&_path), "dummy"); } static void assert_repo_state(git_repository_state_t state) { cl_assert_equal_i(state, git_repository_state(_repo)); } void test_repo_state__none_with_HEAD_attached(void) { assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__none_with_HEAD_detached(void) { cl_git_pass(git_repository_detach_head(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__merge(void) { setup_simple_state(GIT_MERGE_HEAD_FILE); assert_repo_state(GIT_REPOSITORY_STATE_MERGE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__revert(void) { setup_simple_state(GIT_REVERT_HEAD_FILE); assert_repo_state(GIT_REPOSITORY_STATE_REVERT); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__revert_sequence(void) { setup_simple_state(GIT_REVERT_HEAD_FILE); setup_simple_state(GIT_SEQUENCER_TODO_FILE); assert_repo_state(GIT_REPOSITORY_STATE_REVERT_SEQUENCE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__cherry_pick(void) { setup_simple_state(GIT_CHERRYPICK_HEAD_FILE); assert_repo_state(GIT_REPOSITORY_STATE_CHERRYPICK); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__cherrypick_sequence(void) { setup_simple_state(GIT_CHERRYPICK_HEAD_FILE); setup_simple_state(GIT_SEQUENCER_TODO_FILE); assert_repo_state(GIT_REPOSITORY_STATE_CHERRYPICK_SEQUENCE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__bisect(void) { setup_simple_state(GIT_BISECT_LOG_FILE); assert_repo_state(GIT_REPOSITORY_STATE_BISECT); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__rebase_interactive(void) { setup_simple_state(GIT_REBASE_MERGE_INTERACTIVE_FILE); assert_repo_state(GIT_REPOSITORY_STATE_REBASE_INTERACTIVE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__rebase_merge(void) { setup_simple_state(GIT_REBASE_MERGE_DIR "whatever"); assert_repo_state(GIT_REPOSITORY_STATE_REBASE_MERGE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__rebase(void) { setup_simple_state(GIT_REBASE_APPLY_REBASING_FILE); assert_repo_state(GIT_REPOSITORY_STATE_REBASE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__apply_mailbox(void) { setup_simple_state(GIT_REBASE_APPLY_APPLYING_FILE); assert_repo_state(GIT_REPOSITORY_STATE_APPLY_MAILBOX); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); } void test_repo_state__apply_mailbox_or_rebase(void) { setup_simple_state(GIT_REBASE_APPLY_DIR "whatever"); assert_repo_state(GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE); cl_git_pass(git_repository_state_cleanup(_repo)); assert_repo_state(GIT_REPOSITORY_STATE_NONE); }
libgit2-main
tests/libgit2/repo/state.c
#include "clar_libgit2.h" #include "futils.h" #include "repository.h" #include "config.h" #include "path.h" #include "config/config_helpers.h" #include "repo/repo_helpers.h" enum repo_mode { STANDARD_REPOSITORY = 0, BARE_REPOSITORY = 1 }; static git_repository *g_repo = NULL; static git_str g_global_path = GIT_STR_INIT; void test_repo_init__initialize(void) { g_repo = NULL; git_libgit2_opts(GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &g_global_path); } void test_repo_init__cleanup(void) { git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, g_global_path.ptr); git_str_dispose(&g_global_path); cl_fixture_cleanup("tmp_global_path"); } static void cleanup_repository(void *path) { git_repository_free(g_repo); g_repo = NULL; cl_fixture_cleanup((const char *)path); } static void ensure_repository_init( const char *working_directory, int is_bare, const char *expected_path_repository, const char *expected_working_directory) { const char *workdir; cl_assert(!git_fs_path_isdir(working_directory)); cl_git_pass(git_repository_init(&g_repo, working_directory, is_bare)); workdir = git_repository_workdir(g_repo); if (workdir != NULL || expected_working_directory != NULL) { cl_assert( git__suffixcmp(workdir, expected_working_directory) == 0 ); } cl_assert( git__suffixcmp(git_repository_path(g_repo), expected_path_repository) == 0 ); cl_assert(git_repository_is_bare(g_repo) == is_bare); #ifdef GIT_WIN32 if (!is_bare) { DWORD fattrs = GetFileAttributes(git_repository_path(g_repo)); cl_assert((fattrs & FILE_ATTRIBUTE_HIDDEN) != 0); } #endif cl_assert(git_repository_is_empty(g_repo)); } void test_repo_init__standard_repo(void) { cl_set_cleanup(&cleanup_repository, "testrepo"); ensure_repository_init("testrepo/", 0, "testrepo/.git/", "testrepo/"); } void test_repo_init__standard_repo_noslash(void) { cl_set_cleanup(&cleanup_repository, "testrepo"); ensure_repository_init("testrepo", 0, "testrepo/.git/", "testrepo/"); } void test_repo_init__bare_repo(void) { cl_set_cleanup(&cleanup_repository, "testrepo.git"); ensure_repository_init("testrepo.git/", 1, "testrepo.git/", NULL); } void test_repo_init__bare_repo_noslash(void) { cl_set_cleanup(&cleanup_repository, "testrepo.git"); ensure_repository_init("testrepo.git", 1, "testrepo.git/", NULL); } void test_repo_init__bare_repo_escaping_current_workdir(void) { git_str path_repository = GIT_STR_INIT; git_str path_current_workdir = GIT_STR_INIT; cl_git_pass(git_fs_path_prettify_dir(&path_current_workdir, ".", NULL)); cl_git_pass(git_str_joinpath(&path_repository, git_str_cstr(&path_current_workdir), "a/b/c")); cl_git_pass(git_futils_mkdir_r(git_str_cstr(&path_repository), GIT_DIR_MODE)); /* Change the current working directory */ cl_git_pass(chdir(git_str_cstr(&path_repository))); /* Initialize a bare repo with a relative path escaping out of the current working directory */ cl_git_pass(git_repository_init(&g_repo, "../d/e.git", 1)); cl_git_pass(git__suffixcmp(git_repository_path(g_repo), "/a/b/d/e.git/")); git_repository_free(g_repo); g_repo = NULL; /* Open a bare repo with a relative path escaping out of the current working directory */ cl_git_pass(git_repository_open(&g_repo, "../d/e.git")); cl_git_pass(chdir(git_str_cstr(&path_current_workdir))); git_str_dispose(&path_current_workdir); git_str_dispose(&path_repository); cleanup_repository("a"); } void test_repo_init__reinit_bare_repo(void) { cl_set_cleanup(&cleanup_repository, "reinit.git"); /* Initialize the repository */ cl_git_pass(git_repository_init(&g_repo, "reinit.git", 1)); git_repository_free(g_repo); g_repo = NULL; /* Reinitialize the repository */ cl_git_pass(git_repository_init(&g_repo, "reinit.git", 1)); } void test_repo_init__reinit_too_recent_bare_repo(void) { git_config *config; /* Initialize the repository */ cl_git_pass(git_repository_init(&g_repo, "reinit.git", 1)); git_repository_config(&config, g_repo); /* * Hack the config of the repository to make it look like it has * been created by a recenter version of git/libgit2 */ cl_git_pass(git_config_set_int32(config, "core.repositoryformatversion", 42)); git_config_free(config); git_repository_free(g_repo); g_repo = NULL; /* Try to reinitialize the repository */ cl_git_fail(git_repository_init(&g_repo, "reinit.git", 1)); cl_fixture_cleanup("reinit.git"); } void test_repo_init__additional_templates(void) { git_str path = GIT_STR_INIT; cl_set_cleanup(&cleanup_repository, "tester"); ensure_repository_init("tester", 0, "tester/.git/", "tester/"); cl_git_pass( git_str_joinpath(&path, git_repository_path(g_repo), "description")); cl_assert(git_fs_path_isfile(git_str_cstr(&path))); cl_git_pass( git_str_joinpath(&path, git_repository_path(g_repo), "info/exclude")); cl_assert(git_fs_path_isfile(git_str_cstr(&path))); cl_git_pass( git_str_joinpath(&path, git_repository_path(g_repo), "hooks")); cl_assert(git_fs_path_isdir(git_str_cstr(&path))); /* won't confirm specific contents of hooks dir since it may vary */ git_str_dispose(&path); } static void assert_config_entry_on_init_bytype( const char *config_key, int expected_value, bool is_bare) { git_config *config; int error, current_value; const char *repo_path = is_bare ? "config_entry/test.bare.git" : "config_entry/test.non.bare.git"; cl_set_cleanup(&cleanup_repository, "config_entry"); cl_git_pass(git_repository_init(&g_repo, repo_path, is_bare)); cl_git_pass(git_repository_config(&config, g_repo)); error = git_config_get_bool(&current_value, config, config_key); git_config_free(config); if (expected_value >= 0) { cl_assert_equal_i(0, error); cl_assert_equal_i(expected_value, current_value); } else { cl_assert_equal_i(expected_value, error); } } static void assert_config_entry_on_init( const char *config_key, int expected_value) { assert_config_entry_on_init_bytype(config_key, expected_value, true); git_repository_free(g_repo); g_repo = NULL; assert_config_entry_on_init_bytype(config_key, expected_value, false); } void test_repo_init__detect_filemode(void) { assert_config_entry_on_init("core.filemode", cl_is_chmod_supported()); } void test_repo_init__detect_ignorecase(void) { struct stat st; bool found_without_match; cl_git_write2file("testCAPS", "whatever\n", 0, O_CREAT | O_WRONLY, 0666); found_without_match = (p_stat("Testcaps", &st) == 0); cl_must_pass(p_unlink("testCAPS")); assert_config_entry_on_init( "core.ignorecase", found_without_match ? true : GIT_ENOTFOUND); } /* * Windows: if the filesystem supports symlinks (because we're running * as administrator, or because the user has opted into it for normal * users) then we can also opt-in explicitly by settings `core.symlinks` * in the global config. Symlinks remain off by default. */ void test_repo_init__symlinks_win32_enabled_by_global_config(void) { #ifndef GIT_WIN32 cl_skip(); #else git_config *config, *repo_config; int val; if (!git_fs_path_supports_symlinks("link")) cl_skip(); create_tmp_global_config("tmp_global_config", "core.symlinks", "true"); /* * Create a new repository (can't use `assert_config_on_init` since we * want to examine configuration levels with more granularity.) */ cl_git_pass(git_repository_init(&g_repo, "config_entry/test.non.bare.git", false)); /* Ensure that core.symlinks remains set (via the global config). */ cl_git_pass(git_repository_config(&config, g_repo)); cl_git_pass(git_config_get_bool(&val, config, "core.symlinks")); cl_assert_equal_i(1, val); /* * Ensure that the repository config does not set core.symlinks. * It should remain inherited. */ cl_git_pass(git_config_open_level(&repo_config, config, GIT_CONFIG_LEVEL_LOCAL)); cl_git_fail_with(GIT_ENOTFOUND, git_config_get_bool(&val, repo_config, "core.symlinks")); git_config_free(repo_config); git_config_free(config); git_repository_free(g_repo); g_repo = NULL; #endif } void test_repo_init__symlinks_win32_off_by_default(void) { #ifndef GIT_WIN32 cl_skip(); #else assert_config_entry_on_init("core.symlinks", false); #endif } void test_repo_init__symlinks_posix_detected(void) { #ifdef GIT_WIN32 cl_skip(); #else assert_config_entry_on_init( "core.symlinks", git_fs_path_supports_symlinks("link") ? GIT_ENOTFOUND : false); #endif } void test_repo_init__detect_precompose_unicode_required(void) { #ifdef GIT_USE_ICONV char *composed = "ḱṷṓn", *decomposed = "ḱṷṓn"; struct stat st; bool found_with_nfd; cl_git_write2file(composed, "whatever\n", 0, O_CREAT | O_WRONLY, 0666); found_with_nfd = (p_stat(decomposed, &st) == 0); cl_must_pass(p_unlink(composed)); assert_config_entry_on_init("core.precomposeunicode", found_with_nfd); #else assert_config_entry_on_init("core.precomposeunicode", GIT_ENOTFOUND); #endif } void test_repo_init__reinit_doesnot_overwrite_ignorecase(void) { git_config *config; int current_value; /* Init a new repo */ cl_set_cleanup(&cleanup_repository, "not.overwrite.git"); cl_git_pass(git_repository_init(&g_repo, "not.overwrite.git", 1)); /* Change the "core.ignorecase" config value to something unlikely */ git_repository_config(&config, g_repo); git_config_set_int32(config, "core.ignorecase", 42); git_config_free(config); git_repository_free(g_repo); g_repo = NULL; /* Reinit the repository */ cl_git_pass(git_repository_init(&g_repo, "not.overwrite.git", 1)); git_repository_config(&config, g_repo); /* Ensure the "core.ignorecase" config value hasn't been updated */ cl_git_pass(git_config_get_int32(&current_value, config, "core.ignorecase")); cl_assert_equal_i(42, current_value); git_config_free(config); } void test_repo_init__reinit_overwrites_filemode(void) { int expected = cl_is_chmod_supported(), current_value; /* Init a new repo */ cl_set_cleanup(&cleanup_repository, "overwrite.git"); cl_git_pass(git_repository_init(&g_repo, "overwrite.git", 1)); /* Change the "core.filemode" config value to something unlikely */ cl_repo_set_bool(g_repo, "core.filemode", !expected); git_repository_free(g_repo); g_repo = NULL; /* Reinit the repository */ cl_git_pass(git_repository_init(&g_repo, "overwrite.git", 1)); /* Ensure the "core.filemode" config value has been reset */ current_value = cl_repo_get_bool(g_repo, "core.filemode"); cl_assert_equal_i(expected, current_value); } void test_repo_init__sets_logAllRefUpdates_according_to_type_of_repository(void) { assert_config_entry_on_init_bytype("core.logallrefupdates", GIT_ENOTFOUND, true); git_repository_free(g_repo); assert_config_entry_on_init_bytype("core.logallrefupdates", true, false); } void test_repo_init__extended_0(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; /* without MKDIR this should fail */ cl_git_fail(git_repository_init_ext(&g_repo, "extended", &opts)); /* make the directory first, then it should succeed */ cl_git_pass(git_futils_mkdir("extended", 0775, 0)); cl_git_pass(git_repository_init_ext(&g_repo, "extended", &opts)); cl_assert(!git__suffixcmp(git_repository_workdir(g_repo), "/extended/")); cl_assert(!git__suffixcmp(git_repository_path(g_repo), "/extended/.git/")); cl_assert(!git_repository_is_bare(g_repo)); cl_assert(git_repository_is_empty(g_repo)); cleanup_repository("extended"); } void test_repo_init__extended_1(void) { git_reference *ref; git_remote *remote; struct stat st; git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_NO_DOTGIT_DIR; opts.mode = GIT_REPOSITORY_INIT_SHARED_GROUP; opts.workdir_path = "../c_wd"; opts.description = "Awesomest test repository evah"; opts.initial_head = "development"; opts.origin_url = "https://github.com/libgit2/libgit2.git"; cl_git_pass(git_repository_init_ext(&g_repo, "root/b/c.git", &opts)); cl_assert(!git__suffixcmp(git_repository_workdir(g_repo), "/c_wd/")); cl_assert(!git__suffixcmp(git_repository_path(g_repo), "/c.git/")); cl_assert(git_fs_path_isfile("root/b/c_wd/.git")); cl_assert(!git_repository_is_bare(g_repo)); /* repo will not be counted as empty because we set head to "development" */ cl_assert(!git_repository_is_empty(g_repo)); cl_git_pass(git_fs_path_lstat(git_repository_path(g_repo), &st)); cl_assert(S_ISDIR(st.st_mode)); if (cl_is_chmod_supported()) cl_assert((S_ISGID & st.st_mode) == S_ISGID); else cl_assert((S_ISGID & st.st_mode) == 0); cl_git_pass(git_reference_lookup(&ref, g_repo, "HEAD")); cl_assert(git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC); cl_assert_equal_s("refs/heads/development", git_reference_symbolic_target(ref)); git_reference_free(ref); cl_git_pass(git_remote_lookup(&remote, g_repo, "origin")); cl_assert_equal_s("origin", git_remote_name(remote)); cl_assert_equal_s(opts.origin_url, git_remote_url(remote)); git_remote_free(remote); git_repository_free(g_repo); cl_fixture_cleanup("root"); } void test_repo_init__relative_gitdir(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; git_str dot_git_content = GIT_STR_INIT; opts.workdir_path = "../c_wd"; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_RELATIVE_GITLINK | GIT_REPOSITORY_INIT_NO_DOTGIT_DIR; /* make the directory first, then it should succeed */ cl_git_pass(git_repository_init_ext(&g_repo, "root/b/my_repository", &opts)); cl_assert(!git__suffixcmp(git_repository_workdir(g_repo), "root/b/c_wd/")); cl_assert(!git__suffixcmp(git_repository_path(g_repo), "root/b/my_repository/")); cl_assert(!git_repository_is_bare(g_repo)); cl_assert(git_repository_is_empty(g_repo)); /* Verify that the gitlink and worktree entries are relative */ /* Verify worktree */ assert_config_entry_value(g_repo, "core.worktree", "../c_wd/"); /* Verify gitlink */ cl_git_pass(git_futils_readbuffer(&dot_git_content, "root/b/c_wd/.git")); cl_assert_equal_s("gitdir: ../my_repository/", dot_git_content.ptr); git_str_dispose(&dot_git_content); cleanup_repository("root"); } void test_repo_init__relative_gitdir_2(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; git_str dot_git_content = GIT_STR_INIT; git_str full_path = GIT_STR_INIT; cl_git_pass(git_fs_path_prettify(&full_path, ".", NULL)); cl_git_pass(git_str_joinpath(&full_path, full_path.ptr, "root/b/c_wd")); opts.workdir_path = full_path.ptr; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_RELATIVE_GITLINK | GIT_REPOSITORY_INIT_NO_DOTGIT_DIR; /* make the directory first, then it should succeed */ cl_git_pass(git_repository_init_ext(&g_repo, "root/b/my_repository", &opts)); git_str_dispose(&full_path); cl_assert(!git__suffixcmp(git_repository_workdir(g_repo), "root/b/c_wd/")); cl_assert(!git__suffixcmp(git_repository_path(g_repo), "root/b/my_repository/")); cl_assert(!git_repository_is_bare(g_repo)); cl_assert(git_repository_is_empty(g_repo)); /* Verify that the gitlink and worktree entries are relative */ /* Verify worktree */ assert_config_entry_value(g_repo, "core.worktree", "../c_wd/"); /* Verify gitlink */ cl_git_pass(git_futils_readbuffer(&dot_git_content, "root/b/c_wd/.git")); cl_assert_equal_s("gitdir: ../my_repository/", dot_git_content.ptr); git_str_dispose(&dot_git_content); cleanup_repository("root"); } void test_repo_init__can_reinit_an_initialized_repository(void) { git_repository *reinit; cl_set_cleanup(&cleanup_repository, "extended"); cl_git_pass(git_futils_mkdir("extended", 0775, 0)); cl_git_pass(git_repository_init(&g_repo, "extended", false)); cl_git_pass(git_repository_init(&reinit, "extended", false)); cl_assert_equal_s(git_repository_path(g_repo), git_repository_path(reinit)); git_repository_free(reinit); } void test_repo_init__init_with_initial_commit(void) { git_index *index; cl_set_cleanup(&cleanup_repository, "committed"); /* Initialize the repository */ cl_git_pass(git_repository_init(&g_repo, "committed", 0)); /* Index will be automatically created when requested for a new repo */ cl_git_pass(git_repository_index(&index, g_repo)); /* Create a file so we can commit it * * If you are writing code outside the test suite, you can create this * file any way that you like, such as: * FILE *fp = fopen("committed/file.txt", "w"); * fputs("some stuff\n", fp); * fclose(fp); * We like to use the help functions because they do error detection * in a way that's easily compatible with our test suite. */ cl_git_mkfile("committed/file.txt", "some stuff\n"); /* Add file to the index */ cl_git_pass(git_index_add_bypath(index, "file.txt")); cl_git_pass(git_index_write(index)); /* Intentionally not using cl_repo_commit_from_index here so this code * can be used as an example of how an initial commit is typically * made to a repository... */ /* Make sure we're ready to use git_signature_default :-) */ { git_config *cfg, *local; cl_git_pass(git_repository_config(&cfg, g_repo)); cl_git_pass(git_config_open_level(&local, cfg, GIT_CONFIG_LEVEL_LOCAL)); cl_git_pass(git_config_set_string(local, "user.name", "Test User")); cl_git_pass(git_config_set_string(local, "user.email", "[email protected]")); git_config_free(local); git_config_free(cfg); } /* Create a commit with the new contents of the index */ { git_signature *sig; git_oid tree_id, commit_id; git_tree *tree; cl_git_pass(git_signature_default(&sig, g_repo)); cl_git_pass(git_index_write_tree(&tree_id, index)); cl_git_pass(git_tree_lookup(&tree, g_repo, &tree_id)); cl_git_pass(git_commit_create_v( &commit_id, g_repo, "HEAD", sig, sig, NULL, "First", tree, 0)); git_tree_free(tree); git_signature_free(sig); } git_index_free(index); } void test_repo_init__at_filesystem_root(void) { git_repository *repo; const char *sandbox = clar_sandbox_path(); git_str root = GIT_STR_INIT; int root_len; if (!cl_is_env_set("GITTEST_INVASIVE_FS_STRUCTURE")) cl_skip(); root_len = git_fs_path_root(sandbox); cl_assert(root_len >= 0); git_str_put(&root, sandbox, root_len+1); git_str_joinpath(&root, root.ptr, "libgit2_test_dir"); cl_assert(!git_fs_path_exists(root.ptr)); cl_git_pass(git_repository_init(&repo, root.ptr, 0)); cl_assert(git_fs_path_isdir(root.ptr)); cl_git_pass(git_futils_rmdir_r(root.ptr, NULL, GIT_RMDIR_REMOVE_FILES)); git_str_dispose(&root); git_repository_free(repo); } void test_repo_init__nonexisting_directory(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; git_repository *repo; /* * If creating a repo with non-existing parent directories, then libgit2 * will by default create the complete directory hierarchy if using * `git_repository_init`. Thus, let's use the extended version and not * set the `GIT_REPOSITORY_INIT_MKPATH` flag. */ cl_git_fail(git_repository_init_ext(&repo, "nonexisting/path", &opts)); } void test_repo_init__nonexisting_root(void) { #ifdef GIT_WIN32 git_repository *repo; /* * This really only depends on the nonexistence of the Q: drive. We * cannot implement the equivalent test on Unix systems, as there is * fundamentally no path that is disconnected from the root directory. */ cl_git_fail(git_repository_init(&repo, "Q:/non/existent/path", 0)); cl_git_fail(git_repository_init(&repo, "Q:\\non\\existent\\path", 0)); #else clar__skip(); #endif } void test_repo_init__unwriteable_directory(void) { #ifndef GIT_WIN32 git_repository *repo; if (geteuid() == 0) clar__skip(); /* * Create a non-writeable directory so that we cannot create directories * inside of it. The root user has CAP_DAC_OVERRIDE, so he doesn't care * for the directory permissions and thus we need to skip the test if * run as root user. */ cl_must_pass(p_mkdir("unwriteable", 0444)); cl_git_fail(git_repository_init(&repo, "unwriteable/repo", 0)); cl_must_pass(p_rmdir("unwriteable")); #else clar__skip(); #endif } void test_repo_init__defaultbranch_config(void) { git_reference *head; cl_set_cleanup(&cleanup_repository, "repo"); create_tmp_global_config("tmp_global_path", "init.defaultbranch", "my_default_branch"); cl_git_pass(git_repository_init(&g_repo, "repo", 0)); cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD")); cl_assert_equal_s("refs/heads/my_default_branch", git_reference_symbolic_target(head)); git_reference_free(head); } void test_repo_init__defaultbranch_config_empty(void) { git_reference *head; cl_set_cleanup(&cleanup_repository, "repo"); create_tmp_global_config("tmp_global_path", "init.defaultbranch", ""); cl_git_pass(git_repository_init(&g_repo, "repo", 0)); cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD")); cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head)); git_reference_free(head); } void test_repo_init__longpath(void) { #ifdef GIT_WIN32 size_t padding = CONST_STRLEN("objects/pack/pack-.pack.lock") + GIT_OID_SHA1_HEXSIZE; size_t max, i; git_str path = GIT_STR_INIT; git_repository *one = NULL, *two = NULL; /* * Files within repositories need to fit within MAX_PATH; * that means a repo path must be at most (MAX_PATH - 18). */ cl_git_pass(git_str_puts(&path, clar_sandbox_path())); cl_git_pass(git_str_putc(&path, '/')); max = ((MAX_PATH) - path.size) - padding; for (i = 0; i < max - 1; i++) cl_git_pass(git_str_putc(&path, 'a')); cl_git_pass(git_repository_init(&one, path.ptr, 1)); /* Paths longer than this are rejected */ cl_git_pass(git_str_putc(&path, 'z')); cl_git_fail(git_repository_init(&two, path.ptr, 1)); git_repository_free(one); git_repository_free(two); git_str_dispose(&path); #endif }
libgit2-main
tests/libgit2/repo/init.c
#include "clar_libgit2.h" #include "odb.h" #include "futils.h" #include "repository.h" #define TEMP_REPO_FOLDER "temprepo/" #define DISCOVER_FOLDER TEMP_REPO_FOLDER "discover.git" #define SUB_REPOSITORY_FOLDER_NAME "sub_repo" #define SUB_REPOSITORY_FOLDER DISCOVER_FOLDER "/" SUB_REPOSITORY_FOLDER_NAME #define SUB_REPOSITORY_GITDIR SUB_REPOSITORY_FOLDER "/.git" #define SUB_REPOSITORY_FOLDER_SUB SUB_REPOSITORY_FOLDER "/sub" #define SUB_REPOSITORY_FOLDER_SUB_SUB SUB_REPOSITORY_FOLDER_SUB "/subsub" #define SUB_REPOSITORY_FOLDER_SUB_SUB_SUB SUB_REPOSITORY_FOLDER_SUB_SUB "/subsubsub" #define REPOSITORY_ALTERNATE_FOLDER DISCOVER_FOLDER "/alternate_sub_repo" #define REPOSITORY_ALTERNATE_FOLDER_SUB REPOSITORY_ALTERNATE_FOLDER "/sub" #define REPOSITORY_ALTERNATE_FOLDER_SUB_SUB REPOSITORY_ALTERNATE_FOLDER_SUB "/subsub" #define REPOSITORY_ALTERNATE_FOLDER_SUB_SUB_SUB REPOSITORY_ALTERNATE_FOLDER_SUB_SUB "/subsubsub" #define ALTERNATE_MALFORMED_FOLDER1 DISCOVER_FOLDER "/alternate_malformed_repo1" #define ALTERNATE_MALFORMED_FOLDER2 DISCOVER_FOLDER "/alternate_malformed_repo2" #define ALTERNATE_MALFORMED_FOLDER3 DISCOVER_FOLDER "/alternate_malformed_repo3" #define ALTERNATE_NOT_FOUND_FOLDER DISCOVER_FOLDER "/alternate_not_found_repo" static void ensure_repository_discover(const char *start_path, const char *ceiling_dirs, const char *expected_path) { git_buf found_path = GIT_BUF_INIT; git_str resolved = GIT_STR_INIT; git_str_attach(&resolved, p_realpath(expected_path, NULL), 0); cl_assert(resolved.size > 0); cl_git_pass(git_fs_path_to_dir(&resolved)); cl_git_pass(git_repository_discover(&found_path, start_path, 1, ceiling_dirs)); cl_assert_equal_s(found_path.ptr, resolved.ptr); git_str_dispose(&resolved); git_buf_dispose(&found_path); } static void write_file(const char *path, const char *content) { git_file file; int error; if (git_fs_path_exists(path)) { cl_git_pass(p_unlink(path)); } file = git_futils_creat_withpath(path, 0777, 0666); cl_assert(file >= 0); error = p_write(file, content, strlen(content) * sizeof(char)); p_close(file); cl_git_pass(error); } /*no check is performed on ceiling_dirs length, so be sure it's long enough */ static void append_ceiling_dir(git_str *ceiling_dirs, const char *path) { git_str pretty_path = GIT_STR_INIT; char ceiling_separator[2] = { GIT_PATH_LIST_SEPARATOR, '\0' }; cl_git_pass(git_fs_path_prettify_dir(&pretty_path, path, NULL)); if (ceiling_dirs->size > 0) git_str_puts(ceiling_dirs, ceiling_separator); git_str_puts(ceiling_dirs, pretty_path.ptr); git_str_dispose(&pretty_path); cl_assert(git_str_oom(ceiling_dirs) == 0); } static git_buf discovered; static git_str ceiling_dirs; void test_repo_discover__initialize(void) { git_repository *repo; const mode_t mode = 0777; git_futils_mkdir_r(DISCOVER_FOLDER, mode); git_str_init(&ceiling_dirs, 0); append_ceiling_dir(&ceiling_dirs, TEMP_REPO_FOLDER); cl_git_pass(git_repository_init(&repo, DISCOVER_FOLDER, 1)); git_repository_free(repo); cl_git_pass(git_repository_init(&repo, SUB_REPOSITORY_FOLDER, 0)); cl_git_pass(git_futils_mkdir_r(SUB_REPOSITORY_FOLDER_SUB_SUB_SUB, mode)); cl_git_pass(git_futils_mkdir_r(SUB_REPOSITORY_FOLDER_SUB_SUB_SUB, mode)); cl_git_pass(git_futils_mkdir_r(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB_SUB, mode)); write_file(REPOSITORY_ALTERNATE_FOLDER "/" DOT_GIT, "gitdir: ../" SUB_REPOSITORY_FOLDER_NAME "/" DOT_GIT); write_file(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB "/" DOT_GIT, "gitdir: ../../../" SUB_REPOSITORY_FOLDER_NAME "/" DOT_GIT); write_file(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB_SUB "/" DOT_GIT, "gitdir: ../../../../"); cl_git_pass(git_futils_mkdir_r(ALTERNATE_MALFORMED_FOLDER1, mode)); write_file(ALTERNATE_MALFORMED_FOLDER1 "/" DOT_GIT, "Anything but not gitdir:"); cl_git_pass(git_futils_mkdir_r(ALTERNATE_MALFORMED_FOLDER2, mode)); write_file(ALTERNATE_MALFORMED_FOLDER2 "/" DOT_GIT, "gitdir:"); cl_git_pass(git_futils_mkdir_r(ALTERNATE_MALFORMED_FOLDER3, mode)); write_file(ALTERNATE_MALFORMED_FOLDER3 "/" DOT_GIT, "gitdir: \n\n\n"); cl_git_pass(git_futils_mkdir_r(ALTERNATE_NOT_FOUND_FOLDER, mode)); write_file(ALTERNATE_NOT_FOUND_FOLDER "/" DOT_GIT, "gitdir: a_repository_that_surely_does_not_exist"); git_repository_free(repo); } void test_repo_discover__cleanup(void) { git_buf_dispose(&discovered); git_str_dispose(&ceiling_dirs); cl_git_pass(git_futils_rmdir_r(TEMP_REPO_FOLDER, NULL, GIT_RMDIR_REMOVE_FILES)); } void test_repo_discover__discovering_repo_with_exact_path_succeeds(void) { cl_git_pass(git_repository_discover(&discovered, DISCOVER_FOLDER, 0, ceiling_dirs.ptr)); cl_git_pass(git_repository_discover(&discovered, SUB_REPOSITORY_FOLDER, 0, ceiling_dirs.ptr)); } void test_repo_discover__discovering_nonexistent_dir_fails(void) { cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, DISCOVER_FOLDER "-nonexistent", 0, NULL)); } void test_repo_discover__discovering_repo_with_subdirectory_succeeds(void) { ensure_repository_discover(SUB_REPOSITORY_FOLDER_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(SUB_REPOSITORY_FOLDER_SUB_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(SUB_REPOSITORY_FOLDER_SUB_SUB_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); } void test_repo_discover__discovering_repository_with_alternative_gitdir_succeeds(void) { ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB_SUB, ceiling_dirs.ptr, DISCOVER_FOLDER); } void test_repo_discover__discovering_repository_with_malformed_alternative_gitdir_fails(void) { cl_git_fail(git_repository_discover(&discovered, ALTERNATE_MALFORMED_FOLDER1, 0, ceiling_dirs.ptr)); cl_git_fail(git_repository_discover(&discovered, ALTERNATE_MALFORMED_FOLDER2, 0, ceiling_dirs.ptr)); cl_git_fail(git_repository_discover(&discovered, ALTERNATE_MALFORMED_FOLDER3, 0, ceiling_dirs.ptr)); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, ALTERNATE_NOT_FOUND_FOLDER, 0, ceiling_dirs.ptr)); } void test_repo_discover__discovering_repository_with_ceiling(void) { append_ceiling_dir(&ceiling_dirs, SUB_REPOSITORY_FOLDER_SUB); /* this must pass as ceiling_directories cannot prevent the current * working directory to be checked */ ensure_repository_discover(SUB_REPOSITORY_FOLDER, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(SUB_REPOSITORY_FOLDER_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, SUB_REPOSITORY_FOLDER_SUB_SUB, 0, ceiling_dirs.ptr)); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, SUB_REPOSITORY_FOLDER_SUB_SUB_SUB, 0, ceiling_dirs.ptr)); } void test_repo_discover__other_ceiling(void) { append_ceiling_dir(&ceiling_dirs, SUB_REPOSITORY_FOLDER); /* this must pass as ceiling_directories cannot predent the current * working directory to be checked */ ensure_repository_discover(SUB_REPOSITORY_FOLDER, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, SUB_REPOSITORY_FOLDER_SUB, 0, ceiling_dirs.ptr)); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, SUB_REPOSITORY_FOLDER_SUB_SUB, 0, ceiling_dirs.ptr)); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_discover(&discovered, SUB_REPOSITORY_FOLDER_SUB_SUB_SUB, 0, ceiling_dirs.ptr)); } void test_repo_discover__ceiling_should_not_affect_gitdir_redirection(void) { append_ceiling_dir(&ceiling_dirs, SUB_REPOSITORY_FOLDER); /* gitfile redirection should not be affected by ceiling directories */ ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB, ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); ensure_repository_discover(REPOSITORY_ALTERNATE_FOLDER_SUB_SUB_SUB, ceiling_dirs.ptr, DISCOVER_FOLDER); } void test_repo_discover__discovery_starting_at_file_succeeds(void) { int fd; cl_assert((fd = p_creat(SUB_REPOSITORY_FOLDER "/file", 0600)) >= 0); cl_assert(p_close(fd) == 0); ensure_repository_discover(SUB_REPOSITORY_FOLDER "/file", ceiling_dirs.ptr, SUB_REPOSITORY_GITDIR); } void test_repo_discover__discovery_starting_at_system_root_causes_no_hang(void) { #ifdef GIT_WIN32 git_buf out = GIT_BUF_INIT; cl_git_fail(git_repository_discover(&out, "C:/", 0, NULL)); cl_git_fail(git_repository_discover(&out, "//localhost/", 0, NULL)); #endif }
libgit2-main
tests/libgit2/repo/discover.c
#include "clar_libgit2.h" #include "futils.h" #include "repo/repo_helpers.h" #define CLEAR_FOR_CORE_FILEMODE(M) ((M) &= ~0177) static git_repository *_repo = NULL; static mode_t g_umask = 0; static git_str _global_path = GIT_STR_INIT; static const char *fixture_repo; static const char *fixture_templates; void test_repo_template__initialize(void) { _repo = NULL; /* load umask if not already loaded */ if (!g_umask) { g_umask = p_umask(022); (void)p_umask(g_umask); } } void test_repo_template__cleanup(void) { git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, _global_path.ptr); git_str_dispose(&_global_path); cl_fixture_cleanup("tmp_global_path"); if (fixture_repo) { cl_fixture_cleanup(fixture_repo); fixture_repo = NULL; } if (fixture_templates) { cl_fixture_cleanup(fixture_templates); fixture_templates = NULL; } git_repository_free(_repo); _repo = NULL; } static void assert_hooks_match( const char *template_dir, const char *repo_dir, const char *hook_path, bool core_filemode) { git_str expected = GIT_STR_INIT; git_str actual = GIT_STR_INIT; struct stat expected_st, st; cl_git_pass(git_str_joinpath(&expected, template_dir, hook_path)); cl_git_pass(git_fs_path_lstat(expected.ptr, &expected_st)); cl_git_pass(git_str_joinpath(&actual, repo_dir, hook_path)); cl_git_pass(git_fs_path_lstat(actual.ptr, &st)); cl_assert(expected_st.st_size == st.st_size); if (GIT_MODE_TYPE(expected_st.st_mode) != GIT_FILEMODE_LINK) { mode_t expected_mode = GIT_MODE_TYPE(expected_st.st_mode) | (GIT_PERMS_FOR_WRITE(expected_st.st_mode) & ~g_umask); if (!core_filemode) { CLEAR_FOR_CORE_FILEMODE(expected_mode); CLEAR_FOR_CORE_FILEMODE(st.st_mode); } cl_assert_equal_i_fmt(expected_mode, st.st_mode, "%07o"); } git_str_dispose(&expected); git_str_dispose(&actual); } static void assert_mode_seems_okay( const char *base, const char *path, git_filemode_t expect_mode, bool expect_setgid, bool core_filemode) { git_str full = GIT_STR_INIT; struct stat st; cl_git_pass(git_str_joinpath(&full, base, path)); cl_git_pass(git_fs_path_lstat(full.ptr, &st)); git_str_dispose(&full); if (!core_filemode) { CLEAR_FOR_CORE_FILEMODE(expect_mode); CLEAR_FOR_CORE_FILEMODE(st.st_mode); expect_setgid = false; } if (S_ISGID != 0) cl_assert_equal_b(expect_setgid, (st.st_mode & S_ISGID) != 0); cl_assert_equal_b( GIT_PERMS_IS_EXEC(expect_mode), GIT_PERMS_IS_EXEC(st.st_mode)); cl_assert_equal_i_fmt( GIT_MODE_TYPE(expect_mode), GIT_MODE_TYPE(st.st_mode), "%07o"); } static void setup_repo(const char *name, git_repository_init_options *opts) { cl_git_pass(git_repository_init_ext(&_repo, name, opts)); fixture_repo = name; } static void setup_templates(const char *name, bool setup_globally) { git_str path = GIT_STR_INIT; cl_fixture_sandbox("template"); if (strcmp(name, "template")) cl_must_pass(p_rename("template", name)); fixture_templates = name; /* * Create a symlink from link.sample to update.sample if the filesystem * supports it. */ cl_git_pass(git_str_join3(&path, '/', name, "hooks", "link.sample")); #ifdef GIT_WIN32 cl_git_mkfile(path.ptr, "#!/bin/sh\necho hello, world\n"); #else cl_must_pass(p_symlink("update.sample", path.ptr)); #endif git_str_clear(&path); /* Create a file starting with a dot */ cl_git_pass(git_str_join3(&path, '/', name, "hooks", ".dotfile")); cl_git_mkfile(path.ptr, "something\n"); git_str_clear(&path); if (setup_globally) { cl_git_pass(git_str_joinpath(&path, clar_sandbox_path(), name)); create_tmp_global_config("tmp_global_path", "init.templatedir", path.ptr); } git_str_dispose(&path); } static void validate_templates(git_repository *repo, const char *template_path) { git_str path = GIT_STR_INIT, expected = GIT_STR_INIT, actual = GIT_STR_INIT; int filemode; cl_git_pass(git_str_joinpath(&path, template_path, "description")); cl_git_pass(git_futils_readbuffer(&expected, path.ptr)); git_str_clear(&path); cl_git_pass(git_str_joinpath(&path, git_repository_path(repo), "description")); cl_git_pass(git_futils_readbuffer(&actual, path.ptr)); cl_assert_equal_s(expected.ptr, actual.ptr); filemode = cl_repo_get_bool(repo, "core.filemode"); assert_hooks_match( template_path, git_repository_path(repo), "hooks/update.sample", filemode); assert_hooks_match( template_path, git_repository_path(repo), "hooks/link.sample", filemode); assert_hooks_match( template_path, git_repository_path(repo), "hooks/.dotfile", filemode); git_str_dispose(&expected); git_str_dispose(&actual); git_str_dispose(&path); } void test_repo_template__external_templates_specified_in_options(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_BARE | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; opts.template_path = "template"; setup_templates("template", false); setup_repo("templated.git", &opts); validate_templates(_repo, "template"); } void test_repo_template__external_templates_specified_in_config(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_BARE | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; setup_templates("template", true); setup_repo("templated.git", &opts); validate_templates(_repo, "template"); } void test_repo_template__external_templates_with_leading_dot(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_BARE | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; setup_templates(".template_with_leading_dot", true); setup_repo("templated.git", &opts); validate_templates(_repo, ".template_with_leading_dot"); } void test_repo_template__extended_with_template_and_shared_mode(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; const char *repo_path; int filemode; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; opts.template_path = "template"; opts.mode = GIT_REPOSITORY_INIT_SHARED_GROUP; setup_templates("template", false); setup_repo("init_shared_from_tpl", &opts); filemode = cl_repo_get_bool(_repo, "core.filemode"); repo_path = git_repository_path(_repo); assert_mode_seems_okay(repo_path, "hooks", GIT_FILEMODE_TREE | GIT_REPOSITORY_INIT_SHARED_GROUP, true, filemode); assert_mode_seems_okay(repo_path, "info", GIT_FILEMODE_TREE | GIT_REPOSITORY_INIT_SHARED_GROUP, true, filemode); assert_mode_seems_okay(repo_path, "description", GIT_FILEMODE_BLOB, false, filemode); validate_templates(_repo, "template"); } void test_repo_template__templated_head_is_used(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; git_str head = GIT_STR_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; setup_templates("template", true); cl_git_mkfile("template/HEAD", "foobar\n"); setup_repo("repo", &opts); cl_git_pass(git_futils_readbuffer(&head, "repo/.git/HEAD")); cl_assert_equal_s("foobar\n", head.ptr); git_str_dispose(&head); } void test_repo_template__initial_head_option_overrides_template_head(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; git_str head = GIT_STR_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; opts.initial_head = "manual"; setup_templates("template", true); cl_git_mkfile("template/HEAD", "foobar\n"); setup_repo("repo", &opts); cl_git_pass(git_futils_readbuffer(&head, "repo/.git/HEAD")); cl_assert_equal_s("ref: refs/heads/manual\n", head.ptr); git_str_dispose(&head); } void test_repo_template__empty_template_path(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; opts.template_path = ""; setup_repo("foo", &opts); } void test_repo_template__nonexistent_template_path(void) { git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; opts.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; opts.template_path = "/tmp/path/that/does/not/exist/for/libgit2/test"; setup_repo("bar", &opts); }
libgit2-main
tests/libgit2/repo/template.c
#include "clar_libgit2.h" #include "../submodule/submodule_helpers.h" #include "repository.h" void test_repo_reservedname__cleanup(void) { cl_git_sandbox_cleanup(); } void test_repo_reservedname__includes_shortname_on_win32(void) { git_repository *repo; git_str *reserved; size_t reserved_len; repo = cl_git_sandbox_init("nasty"); cl_assert(git_repository__reserved_names(&reserved, &reserved_len, repo, false)); #ifdef GIT_WIN32 cl_assert_equal_i(2, reserved_len); cl_assert_equal_s(".git", reserved[0].ptr); cl_assert_equal_s("GIT~1", reserved[1].ptr); #else cl_assert_equal_i(1, reserved_len); cl_assert_equal_s(".git", reserved[0].ptr); #endif } void test_repo_reservedname__includes_shortname_when_requested(void) { git_repository *repo; git_str *reserved; size_t reserved_len; repo = cl_git_sandbox_init("nasty"); cl_assert(git_repository__reserved_names(&reserved, &reserved_len, repo, true)); cl_assert_equal_i(2, reserved_len); cl_assert_equal_s(".git", reserved[0].ptr); cl_assert_equal_s("GIT~1", reserved[1].ptr); } /* Ensures that custom shortnames are included: creates a GIT~1 so that the * .git folder itself will have to be named GIT~2 */ void test_repo_reservedname__custom_shortname_recognized(void) { #ifdef GIT_WIN32 git_repository *repo; git_str *reserved; size_t reserved_len; if (!cl_sandbox_supports_8dot3()) clar__skip(); repo = cl_git_sandbox_init("nasty"); cl_must_pass(p_rename("nasty/.git", "nasty/_temp")); cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666); cl_must_pass(p_rename("nasty/_temp", "nasty/.git")); cl_assert(git_repository__reserved_names(&reserved, &reserved_len, repo, true)); cl_assert_equal_i(3, reserved_len); cl_assert_equal_s(".git", reserved[0].ptr); cl_assert_equal_s("GIT~1", reserved[1].ptr); cl_assert_equal_s("GIT~2", reserved[2].ptr); #endif } /* When looking at the short name for a submodule, we need to prevent * people from overwriting the `.git` file in the submodule working * directory itself. We don't want to look at the actual repository * path, since it will be in the super's repository above us, and * typically named with the name of our subrepository. Consequently, * preventing access to the short name of the actual repository path * would prevent us from creating files with the same name as the * subrepo. (Eg, a submodule named "libgit2" could not contain a file * named "libgit2", which would be unfortunate.) */ void test_repo_reservedname__submodule_pointer(void) { #ifdef GIT_WIN32 git_repository *super_repo, *sub_repo; git_submodule *sub; git_str *sub_reserved; size_t sub_reserved_len; if (!cl_sandbox_supports_8dot3()) clar__skip(); super_repo = setup_fixture_submod2(); assert_submodule_exists(super_repo, "sm_unchanged"); cl_git_pass(git_submodule_lookup(&sub, super_repo, "sm_unchanged")); cl_git_pass(git_submodule_open(&sub_repo, sub)); cl_assert(git_repository__reserved_names(&sub_reserved, &sub_reserved_len, sub_repo, true)); cl_assert_equal_i(2, sub_reserved_len); cl_assert_equal_s(".git", sub_reserved[0].ptr); cl_assert_equal_s("GIT~1", sub_reserved[1].ptr); git_submodule_free(sub); git_repository_free(sub_repo); #endif } /* Like the `submodule_pointer` test (above), this ensures that we do not * follow the gitlink to the submodule's repository location and treat that * as a reserved name. This tests at an initial submodule update, where the * submodule repo is being created. */ void test_repo_reservedname__submodule_pointer_during_create(void) { git_repository *repo; git_submodule *sm; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; git_str url = GIT_STR_INIT; repo = setup_fixture_super(); cl_git_pass(git_str_joinpath(&url, clar_sandbox_path(), "sub.git")); cl_repo_set_string(repo, "submodule.sub.url", url.ptr); cl_git_pass(git_submodule_lookup(&sm, repo, "sub")); cl_git_pass(git_submodule_update(sm, 1, &update_options)); git_submodule_free(sm); git_str_dispose(&url); }
libgit2-main
tests/libgit2/repo/reservedname.c
#include "clar_libgit2.h" #include "futils.h" #include "sysdir.h" #include <ctype.h> git_repository *repo; void test_repo_extensions__initialize(void) { git_config *config; repo = cl_git_sandbox_init("empty_bare.git"); cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_int32(config, "core.repositoryformatversion", 1)); git_config_free(config); } void test_repo_extensions__cleanup(void) { cl_git_sandbox_cleanup(); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_EXTENSIONS, NULL, 0)); } void test_repo_extensions__builtin(void) { git_repository *extended; cl_repo_set_string(repo, "extensions.noop", "foobar"); cl_git_pass(git_repository_open(&extended, "empty_bare.git")); cl_assert(git_repository_path(extended) != NULL); cl_assert(git__suffixcmp(git_repository_path(extended), "/") == 0); git_repository_free(extended); } void test_repo_extensions__negate_builtin(void) { const char *in[] = { "foo", "!noop", "baz" }; git_repository *extended; cl_repo_set_string(repo, "extensions.noop", "foobar"); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_EXTENSIONS, in, ARRAY_SIZE(in))); cl_git_fail(git_repository_open(&extended, "empty_bare.git")); git_repository_free(extended); } void test_repo_extensions__unsupported(void) { git_repository *extended = NULL; cl_repo_set_string(repo, "extensions.unknown", "foobar"); cl_git_fail(git_repository_open(&extended, "empty_bare.git")); git_repository_free(extended); } void test_repo_extensions__adds_extension(void) { const char *in[] = { "foo", "!noop", "newextension", "baz" }; git_repository *extended; cl_repo_set_string(repo, "extensions.newextension", "foobar"); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_EXTENSIONS, in, ARRAY_SIZE(in))); cl_git_pass(git_repository_open(&extended, "empty_bare.git")); cl_assert(git_repository_path(extended) != NULL); cl_assert(git__suffixcmp(git_repository_path(extended), "/") == 0); git_repository_free(extended); }
libgit2-main
tests/libgit2/repo/extensions.c
#include "clar_libgit2.h" #include "futils.h" static git_repository *g_repo; void test_repo_shallow__initialize(void) { } void test_repo_shallow__cleanup(void) { cl_git_sandbox_cleanup(); } void test_repo_shallow__no_shallow_file(void) { g_repo = cl_git_sandbox_init("testrepo.git"); cl_assert_equal_i(0, git_repository_is_shallow(g_repo)); } void test_repo_shallow__empty_shallow_file(void) { g_repo = cl_git_sandbox_init("testrepo.git"); cl_git_mkfile("testrepo.git/shallow", ""); cl_assert_equal_i(0, git_repository_is_shallow(g_repo)); } void test_repo_shallow__shallow_repo(void) { g_repo = cl_git_sandbox_init("shallow.git"); cl_assert_equal_i(1, git_repository_is_shallow(g_repo)); } void test_repo_shallow__clears_errors(void) { g_repo = cl_git_sandbox_init("testrepo.git"); cl_assert_equal_i(0, git_repository_is_shallow(g_repo)); cl_assert_equal_p(NULL, git_error_last()); }
libgit2-main
tests/libgit2/repo/shallow.c
#include "clar_libgit2.h" #include "futils.h" #include "sysdir.h" #include <ctype.h> static void clear_git_env(void) { cl_setenv("GIT_DIR", NULL); cl_setenv("GIT_CEILING_DIRECTORIES", NULL); cl_setenv("GIT_INDEX_FILE", NULL); cl_setenv("GIT_NAMESPACE", NULL); cl_setenv("GIT_OBJECT_DIRECTORY", NULL); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", NULL); cl_setenv("GIT_WORK_TREE", NULL); cl_setenv("GIT_COMMON_DIR", NULL); } void test_repo_env__initialize(void) { clear_git_env(); } void test_repo_env__cleanup(void) { cl_git_sandbox_cleanup(); if (git_fs_path_isdir("attr")) git_futils_rmdir_r("attr", NULL, GIT_RMDIR_REMOVE_FILES); if (git_fs_path_isdir("testrepo.git")) git_futils_rmdir_r("testrepo.git", NULL, GIT_RMDIR_REMOVE_FILES); if (git_fs_path_isdir("peeled.git")) git_futils_rmdir_r("peeled.git", NULL, GIT_RMDIR_REMOVE_FILES); clear_git_env(); } static int GIT_FORMAT_PRINTF(2, 3) cl_setenv_printf(const char *name, const char *fmt, ...) { int ret; va_list args; git_str buf = GIT_STR_INIT; va_start(args, fmt); cl_git_pass(git_str_vprintf(&buf, fmt, args)); va_end(args); ret = cl_setenv(name, git_str_cstr(&buf)); git_str_dispose(&buf); return ret; } /* Helper functions for test_repo_open__env, passing through the file and line * from the caller rather than those of the helper. The expression strings * distinguish between the possible failures within the helper. */ static void env_pass_(const char *path, const char *file, const char *func, int line) { git_repository *repo; cl_git_expect(git_repository_open_ext(NULL, path, GIT_REPOSITORY_OPEN_FROM_ENV, NULL), 0, file, func, line); cl_git_expect(git_repository_open_ext(&repo, path, GIT_REPOSITORY_OPEN_FROM_ENV, NULL), 0, file, func, line); cl_assert_at_line(git__suffixcmp(git_repository_path(repo), "attr/.git/") == 0, file, func, line); cl_assert_at_line(git__suffixcmp(git_repository_workdir(repo), "attr/") == 0, file, func, line); cl_assert_at_line(!git_repository_is_bare(repo), file, func, line); git_repository_free(repo); } #define env_pass(path) env_pass_((path), __FILE__, __func__, __LINE__) #define cl_git_fail_at_line(expr, file, func, line) clar__assert((expr) < 0, file, func, line, "Expected function call to fail: " #expr, NULL, 1) static void env_fail_(const char *path, const char *file, const char *func, int line) { git_repository *repo; cl_git_fail_at_line(git_repository_open_ext(NULL, path, GIT_REPOSITORY_OPEN_FROM_ENV, NULL), file, func, line); cl_git_fail_at_line(git_repository_open_ext(&repo, path, GIT_REPOSITORY_OPEN_FROM_ENV, NULL), file, func, line); } #define env_fail(path) env_fail_((path), __FILE__, __func__, __LINE__) static void env_cd_( const char *path, void (*passfail_)(const char *, const char *, const char *, int), const char *file, const char *func, int line) { git_str cwd_buf = GIT_STR_INIT; cl_git_pass(git_fs_path_prettify_dir(&cwd_buf, ".", NULL)); cl_must_pass(p_chdir(path)); passfail_(NULL, file, func, line); cl_must_pass(p_chdir(git_str_cstr(&cwd_buf))); git_str_dispose(&cwd_buf); } #define env_cd_pass(path) env_cd_((path), env_pass_, __FILE__, __func__, __LINE__) #define env_cd_fail(path) env_cd_((path), env_fail_, __FILE__, __func__, __LINE__) static void env_check_objects_(bool a, bool t, bool p, const char *file, const char *func, int line) { git_repository *repo; git_oid oid_a, oid_t, oid_p; git_object *object; cl_git_pass(git_oid__fromstr(&oid_a, "45141a79a77842c59a63229403220a4e4be74e3d", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&oid_t, "1385f264afb75a56a5bec74243be9b367ba4ca08", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&oid_p, "0df1a5865c8abfc09f1f2182e6a31be550e99f07", GIT_OID_SHA1)); cl_git_expect(git_repository_open_ext(&repo, "attr", GIT_REPOSITORY_OPEN_FROM_ENV, NULL), 0, file, func, line); if (a) { cl_git_expect(git_object_lookup(&object, repo, &oid_a, GIT_OBJECT_BLOB), 0, file, func, line); git_object_free(object); } else { cl_git_fail_at_line(git_object_lookup(&object, repo, &oid_a, GIT_OBJECT_BLOB), file, func, line); } if (t) { cl_git_expect(git_object_lookup(&object, repo, &oid_t, GIT_OBJECT_BLOB), 0, file, func, line); git_object_free(object); } else { cl_git_fail_at_line(git_object_lookup(&object, repo, &oid_t, GIT_OBJECT_BLOB), file, func, line); } if (p) { cl_git_expect(git_object_lookup(&object, repo, &oid_p, GIT_OBJECT_COMMIT), 0, file, func, line); git_object_free(object); } else { cl_git_fail_at_line(git_object_lookup(&object, repo, &oid_p, GIT_OBJECT_COMMIT), file, func, line); } git_repository_free(repo); } #define env_check_objects(a, t, t2) env_check_objects_((a), (t), (t2), __FILE__, __func__, __LINE__) void test_repo_env__open(void) { git_repository *repo = NULL; git_str repo_dir_buf = GIT_STR_INIT; const char *repo_dir = NULL; git_index *index = NULL; const char *t_obj = "testrepo.git/objects"; const char *p_obj = "peeled.git/objects"; clear_git_env(); cl_fixture_sandbox("attr"); cl_fixture_sandbox("testrepo.git"); cl_fixture_sandbox("peeled.git"); cl_git_pass(p_rename("attr/.gitted", "attr/.git")); cl_git_pass(git_fs_path_prettify_dir(&repo_dir_buf, "attr", NULL)); repo_dir = git_str_cstr(&repo_dir_buf); /* GIT_DIR that doesn't exist */ cl_setenv("GIT_DIR", "does-not-exist"); env_fail(NULL); /* Explicit start_path overrides GIT_DIR */ env_pass("attr"); env_pass("attr/.git"); env_pass("attr/sub"); env_pass("attr/sub/sub"); /* GIT_DIR with relative paths */ cl_setenv("GIT_DIR", "attr/.git"); env_pass(NULL); cl_setenv("GIT_DIR", "attr"); env_fail(NULL); cl_setenv("GIT_DIR", "attr/sub"); env_fail(NULL); cl_setenv("GIT_DIR", "attr/sub/sub"); env_fail(NULL); /* GIT_DIR with absolute paths */ cl_setenv_printf("GIT_DIR", "%s/.git", repo_dir); env_pass(NULL); cl_setenv("GIT_DIR", repo_dir); env_fail(NULL); cl_setenv_printf("GIT_DIR", "%s/sub", repo_dir); env_fail(NULL); cl_setenv_printf("GIT_DIR", "%s/sub/sub", repo_dir); env_fail(NULL); cl_setenv("GIT_DIR", NULL); /* Searching from the current directory */ env_cd_pass("attr"); env_cd_pass("attr/.git"); env_cd_pass("attr/sub"); env_cd_pass("attr/sub/sub"); /* A ceiling directory blocks searches from ascending into that * directory, but doesn't block the start_path itself. */ cl_setenv("GIT_CEILING_DIRECTORIES", repo_dir); env_cd_pass("attr"); env_cd_fail("attr/sub"); env_cd_fail("attr/sub/sub"); cl_setenv_printf("GIT_CEILING_DIRECTORIES", "%s/sub", repo_dir); env_cd_pass("attr"); env_cd_pass("attr/sub"); env_cd_fail("attr/sub/sub"); /* Multiple ceiling directories */ cl_setenv_printf("GIT_CEILING_DIRECTORIES", "123%c%s/sub%cabc", GIT_PATH_LIST_SEPARATOR, repo_dir, GIT_PATH_LIST_SEPARATOR); env_cd_pass("attr"); env_cd_pass("attr/sub"); env_cd_fail("attr/sub/sub"); cl_setenv_printf("GIT_CEILING_DIRECTORIES", "%s%c%s/sub", repo_dir, GIT_PATH_LIST_SEPARATOR, repo_dir); env_cd_pass("attr"); env_cd_fail("attr/sub"); env_cd_fail("attr/sub/sub"); cl_setenv_printf("GIT_CEILING_DIRECTORIES", "%s/sub%c%s", repo_dir, GIT_PATH_LIST_SEPARATOR, repo_dir); env_cd_pass("attr"); env_cd_fail("attr/sub"); env_cd_fail("attr/sub/sub"); cl_setenv_printf("GIT_CEILING_DIRECTORIES", "%s%c%s/sub/sub", repo_dir, GIT_PATH_LIST_SEPARATOR, repo_dir); env_cd_pass("attr"); env_cd_fail("attr/sub"); env_cd_fail("attr/sub/sub"); cl_setenv("GIT_CEILING_DIRECTORIES", NULL); /* Index files */ cl_setenv("GIT_INDEX_FILE", cl_fixture("gitgit.index")); cl_git_pass(git_repository_open_ext(&repo, "attr", GIT_REPOSITORY_OPEN_FROM_ENV, NULL)); cl_git_pass(git_repository_index(&index, repo)); cl_assert_equal_s(git_index_path(index), cl_fixture("gitgit.index")); cl_assert_equal_i(git_index_entrycount(index), 1437); git_index_free(index); git_repository_free(repo); cl_setenv("GIT_INDEX_FILE", NULL); /* Namespaces */ cl_setenv("GIT_NAMESPACE", "some-namespace"); cl_git_pass(git_repository_open_ext(&repo, "attr", GIT_REPOSITORY_OPEN_FROM_ENV, NULL)); cl_assert_equal_s(git_repository_get_namespace(repo), "some-namespace"); git_repository_free(repo); cl_setenv("GIT_NAMESPACE", NULL); /* Object directories and alternates */ env_check_objects(true, false, false); cl_setenv("GIT_OBJECT_DIRECTORY", t_obj); env_check_objects(false, true, false); cl_setenv("GIT_OBJECT_DIRECTORY", NULL); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", t_obj); env_check_objects(true, true, false); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", NULL); cl_setenv("GIT_OBJECT_DIRECTORY", p_obj); env_check_objects(false, false, true); cl_setenv("GIT_OBJECT_DIRECTORY", NULL); cl_setenv("GIT_OBJECT_DIRECTORY", t_obj); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", p_obj); env_check_objects(false, true, true); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", NULL); cl_setenv("GIT_OBJECT_DIRECTORY", NULL); cl_setenv_printf("GIT_ALTERNATE_OBJECT_DIRECTORIES", "%s%c%s", t_obj, GIT_PATH_LIST_SEPARATOR, p_obj); env_check_objects(true, true, true); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", NULL); cl_setenv_printf("GIT_ALTERNATE_OBJECT_DIRECTORIES", "%s%c%s", p_obj, GIT_PATH_LIST_SEPARATOR, t_obj); env_check_objects(true, true, true); cl_setenv("GIT_ALTERNATE_OBJECT_DIRECTORIES", NULL); cl_fixture_cleanup("peeled.git"); cl_fixture_cleanup("testrepo.git"); cl_fixture_cleanup("attr"); git_str_dispose(&repo_dir_buf); clear_git_env(); }
libgit2-main
tests/libgit2/repo/env.c
#include "clar_libgit2.h" #include "refs.h" #include "repo_helpers.h" #include "posix.h" #include "git2/annotated_commit.h" static const char *g_email = "[email protected]"; static git_repository *repo; void test_repo_head__initialize(void) { repo = cl_git_sandbox_init("testrepo.git"); cl_git_pass(git_repository_set_ident(repo, "Foo Bar", g_email)); } void test_repo_head__cleanup(void) { cl_git_sandbox_cleanup(); } void test_repo_head__unborn_head(void) { git_reference *ref; cl_git_pass(git_repository_head_detached(repo)); make_head_unborn(repo, NON_EXISTING_HEAD); cl_assert(git_repository_head_unborn(repo) == 1); /* take the repo back to it's original state */ cl_git_pass(git_reference_symbolic_create(&ref, repo, "HEAD", "refs/heads/master", 1, NULL)); cl_assert(git_repository_head_unborn(repo) == 0); git_reference_free(ref); } void test_repo_head__set_head_Attaches_HEAD_to_un_unborn_branch_when_the_branch_doesnt_exist(void) { git_reference *head; cl_git_pass(git_repository_set_head(repo, "refs/heads/doesnt/exist/yet")); cl_assert_equal_i(false, git_repository_head_detached(repo)); cl_assert_equal_i(GIT_EUNBORNBRANCH, git_repository_head(&head, repo)); } void test_repo_head__set_head_Returns_ENOTFOUND_when_the_reference_doesnt_exist(void) { cl_assert_equal_i(GIT_ENOTFOUND, git_repository_set_head(repo, "refs/tags/doesnt/exist/yet")); } void test_repo_head__set_head_Fails_when_the_reference_points_to_a_non_commitish(void) { cl_git_fail(git_repository_set_head(repo, "refs/tags/point_to_blob")); } void test_repo_head__set_head_Attaches_HEAD_when_the_reference_points_to_a_branch(void) { git_reference *head; cl_git_pass(git_repository_set_head(repo, "refs/heads/br2")); cl_assert_equal_i(false, git_repository_head_detached(repo)); cl_git_pass(git_repository_head(&head, repo)); cl_assert_equal_s("refs/heads/br2", git_reference_name(head)); git_reference_free(head); } static void assert_head_is_correctly_detached(void) { git_reference *head; git_object *commit; cl_assert_equal_i(true, git_repository_head_detached(repo)); cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_object_lookup(&commit, repo, git_reference_target(head), GIT_OBJECT_COMMIT)); git_object_free(commit); git_reference_free(head); } void test_repo_head__set_head_Detaches_HEAD_when_the_reference_doesnt_point_to_a_branch(void) { cl_git_pass(git_repository_set_head(repo, "refs/tags/test")); cl_assert_equal_i(true, git_repository_head_detached(repo)); assert_head_is_correctly_detached(); } void test_repo_head__set_head_detached_Return_ENOTFOUND_when_the_object_doesnt_exist(void) { git_oid oid; cl_git_pass(git_oid__fromstr(&oid, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", GIT_OID_SHA1)); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_set_head_detached(repo, &oid)); } void test_repo_head__set_head_detached_Fails_when_the_object_isnt_a_commitish(void) { git_object *blob; cl_git_pass(git_revparse_single(&blob, repo, "point_to_blob")); cl_git_fail(git_repository_set_head_detached(repo, git_object_id(blob))); git_object_free(blob); } void test_repo_head__set_head_detached_Detaches_HEAD_and_make_it_point_to_the_peeled_commit(void) { git_object *tag; cl_git_pass(git_revparse_single(&tag, repo, "tags/test")); cl_assert_equal_i(GIT_OBJECT_TAG, git_object_type(tag)); cl_git_pass(git_repository_set_head_detached(repo, git_object_id(tag))); assert_head_is_correctly_detached(); git_object_free(tag); } void test_repo_head__detach_head_Detaches_HEAD_and_make_it_point_to_the_peeled_commit(void) { cl_assert_equal_i(false, git_repository_head_detached(repo)); cl_git_pass(git_repository_detach_head(repo)); assert_head_is_correctly_detached(); } void test_repo_head__detach_head_Fails_if_HEAD_and_point_to_a_non_commitish(void) { git_reference *head; cl_git_pass(git_reference_symbolic_create(&head, repo, GIT_HEAD_FILE, "refs/tags/point_to_blob", 1, NULL)); cl_git_fail(git_repository_detach_head(repo)); git_reference_free(head); } void test_repo_head__detaching_an_unborn_branch_returns_GIT_EUNBORNBRANCH(void) { make_head_unborn(repo, NON_EXISTING_HEAD); cl_assert_equal_i(GIT_EUNBORNBRANCH, git_repository_detach_head(repo)); } void test_repo_head__retrieving_an_unborn_branch_returns_GIT_EUNBORNBRANCH(void) { git_reference *head; make_head_unborn(repo, NON_EXISTING_HEAD); cl_assert_equal_i(GIT_EUNBORNBRANCH, git_repository_head(&head, repo)); } void test_repo_head__retrieving_a_missing_head_returns_GIT_ENOTFOUND(void) { git_reference *head; delete_head(repo); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_head(&head, repo)); } void test_repo_head__can_tell_if_an_unborn_head_is_detached(void) { make_head_unborn(repo, NON_EXISTING_HEAD); cl_assert_equal_i(false, git_repository_head_detached(repo)); }
libgit2-main
tests/libgit2/repo/head.c
#include "clar_libgit2.h" #include "sysdir.h" #include "futils.h" #include <ctype.h> static git_str path = GIT_STR_INIT; void test_repo_config__initialize(void) { cl_fixture_sandbox("empty_standard_repo"); cl_git_pass(cl_rename( "empty_standard_repo/.gitted", "empty_standard_repo/.git")); git_str_clear(&path); cl_must_pass(p_mkdir("alternate", 0777)); cl_git_pass(git_fs_path_prettify(&path, "alternate", NULL)); } void test_repo_config__cleanup(void) { cl_sandbox_set_search_path_defaults(); git_str_dispose(&path); cl_git_pass( git_futils_rmdir_r("alternate", NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert(!git_fs_path_isdir("alternate")); cl_fixture_cleanup("empty_standard_repo"); } void test_repo_config__can_open_global_when_there_is_no_file(void) { git_repository *repo; git_config *config, *global; cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr)); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_open_level( &global, config, GIT_CONFIG_LEVEL_GLOBAL)); cl_git_pass(git_config_set_string(global, "test.set", "42")); git_config_free(global); git_config_free(config); git_repository_free(repo); } void test_repo_config__can_open_missing_global_with_separators(void) { git_repository *repo; git_config *config, *global; cl_git_pass(git_str_printf( &path, "%c%s", GIT_PATH_LIST_SEPARATOR, "dummy")); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr)); git_str_dispose(&path); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_open_level( &global, config, GIT_CONFIG_LEVEL_GLOBAL)); cl_git_pass(git_config_set_string(global, "test.set", "42")); git_config_free(global); git_config_free(config); git_repository_free(repo); } #include "repository.h" void test_repo_config__read_with_no_configs_at_all(void) { git_repository *repo; int val; cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr)); /* with none */ cl_must_pass(p_unlink("empty_standard_repo/.git/config")); cl_assert(!git_fs_path_isfile("empty_standard_repo/.git/config")); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(GIT_ABBREV_DEFAULT, val); git_repository_free(repo); /* with no local config, just system */ cl_sandbox_set_search_path_defaults(); cl_must_pass(p_mkdir("alternate/1", 0777)); cl_git_pass(git_str_joinpath(&path, path.ptr, "1")); cl_git_rewritefile("alternate/1/gitconfig", "[core]\n\tabbrev = 10\n"); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr)); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(10, val); git_repository_free(repo); /* with just xdg + system */ cl_must_pass(p_mkdir("alternate/2", 0777)); path.ptr[path.size - 1] = '2'; cl_git_rewritefile("alternate/2/config", "[core]\n\tabbrev = 20\n"); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr)); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(20, val); git_repository_free(repo); /* with global + xdg + system */ cl_must_pass(p_mkdir("alternate/3", 0777)); path.ptr[path.size - 1] = '3'; cl_git_rewritefile("alternate/3/.gitconfig", "[core]\n\tabbrev = 30\n"); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(30, val); git_repository_free(repo); /* with all configs */ cl_git_rewritefile("empty_standard_repo/.git/config", "[core]\n\tabbrev = 40\n"); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(40, val); git_repository_free(repo); /* with all configs but delete the files ? */ cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(40, val); cl_must_pass(p_unlink("empty_standard_repo/.git/config")); cl_assert(!git_fs_path_isfile("empty_standard_repo/.git/config")); cl_must_pass(p_unlink("alternate/1/gitconfig")); cl_assert(!git_fs_path_isfile("alternate/1/gitconfig")); cl_must_pass(p_unlink("alternate/2/config")); cl_assert(!git_fs_path_isfile("alternate/2/config")); cl_must_pass(p_unlink("alternate/3/.gitconfig")); cl_assert(!git_fs_path_isfile("alternate/3/.gitconfig")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(40, val); git_repository_free(repo); /* reopen */ cl_assert(!git_fs_path_isfile("empty_standard_repo/.git/config")); cl_assert(!git_fs_path_isfile("alternate/3/.gitconfig")); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository__configmap_lookup_cache_clear(repo); val = -1; cl_git_pass(git_repository__configmap_lookup(&val, repo, GIT_CONFIGMAP_ABBREV)); cl_assert_equal_i(7, val); git_repository_free(repo); cl_assert(!git_fs_path_exists("empty_standard_repo/.git/config")); cl_assert(!git_fs_path_exists("alternate/3/.gitconfig")); }
libgit2-main
tests/libgit2/repo/config.c
#include "clar_libgit2.h" #include "odb.h" static git_repository *_repo; void test_repo_hashfile__initialize(void) { _repo = cl_git_sandbox_init("status"); } void test_repo_hashfile__cleanup(void) { cl_fixture_cleanup("absolute"); cl_git_sandbox_cleanup(); _repo = NULL; } void test_repo_hashfile__simple(void) { git_oid a, b; git_str full = GIT_STR_INIT; /* hash with repo relative path */ cl_git_pass(git_odb__hashfile(&a, "status/current_file", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "current_file", GIT_OBJECT_BLOB, NULL)); cl_assert_equal_oid(&a, &b); cl_git_pass(git_str_joinpath(&full, git_repository_workdir(_repo), "current_file")); /* hash with full path */ cl_git_pass(git_odb__hashfile(&a, full.ptr, GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, full.ptr, GIT_OBJECT_BLOB, NULL)); cl_assert_equal_oid(&a, &b); /* hash with invalid type */ cl_git_fail(git_odb__hashfile(&a, full.ptr, GIT_OBJECT_ANY, GIT_OID_SHA1)); cl_git_fail(git_repository_hashfile(&b, _repo, full.ptr, GIT_OBJECT_OFS_DELTA, NULL)); git_str_dispose(&full); } void test_repo_hashfile__filtered_in_workdir(void) { git_str root = GIT_STR_INIT, txt = GIT_STR_INIT, bin = GIT_STR_INIT; char cwd[GIT_PATH_MAX]; git_oid a, b; cl_must_pass(p_getcwd(cwd, GIT_PATH_MAX)); cl_must_pass(p_mkdir("absolute", 0777)); cl_git_pass(git_str_joinpath(&root, cwd, "status")); cl_git_pass(git_str_joinpath(&txt, root.ptr, "testfile.txt")); cl_git_pass(git_str_joinpath(&bin, root.ptr, "testfile.bin")); cl_repo_set_bool(_repo, "core.autocrlf", true); cl_git_append2file("status/.gitattributes", "*.txt text\n*.bin binary\n\n"); /* create some sample content with CRLF in it */ cl_git_mkfile("status/testfile.txt", "content\r\n"); cl_git_mkfile("status/testfile.bin", "other\r\nstuff\r\n"); /* not equal hashes because of filtering */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "testfile.txt", GIT_OBJECT_BLOB, NULL)); cl_assert(git_oid_cmp(&a, &b)); /* not equal hashes because of filtering when specified by absolute path */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, txt.ptr, GIT_OBJECT_BLOB, NULL)); cl_assert(git_oid_cmp(&a, &b)); /* equal hashes because filter is binary */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "testfile.bin", GIT_OBJECT_BLOB, NULL)); cl_assert_equal_oid(&a, &b); /* equal hashes because filter is binary when specified by absolute path */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, bin.ptr, GIT_OBJECT_BLOB, NULL)); cl_assert_equal_oid(&a, &b); /* equal hashes when 'as_file' points to binary filtering */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "testfile.txt", GIT_OBJECT_BLOB, "foo.bin")); cl_assert_equal_oid(&a, &b); /* equal hashes when 'as_file' points to binary filtering (absolute path) */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, txt.ptr, GIT_OBJECT_BLOB, "foo.bin")); cl_assert_equal_oid(&a, &b); /* not equal hashes when 'as_file' points to text filtering */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "testfile.bin", GIT_OBJECT_BLOB, "foo.txt")); cl_assert(git_oid_cmp(&a, &b)); /* not equal hashes when 'as_file' points to text filtering */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, bin.ptr, GIT_OBJECT_BLOB, "foo.txt")); cl_assert(git_oid_cmp(&a, &b)); /* equal hashes when 'as_file' is empty and turns off filtering */ cl_git_pass(git_odb__hashfile(&a, "status/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "testfile.txt", GIT_OBJECT_BLOB, "")); cl_assert_equal_oid(&a, &b); cl_git_pass(git_odb__hashfile(&a, "status/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, "testfile.bin", GIT_OBJECT_BLOB, "")); cl_assert_equal_oid(&a, &b); cl_git_pass(git_odb__hashfile(&a, "status/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, txt.ptr, GIT_OBJECT_BLOB, "")); cl_assert_equal_oid(&a, &b); cl_git_pass(git_odb__hashfile(&a, "status/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, bin.ptr, GIT_OBJECT_BLOB, "")); cl_assert_equal_oid(&a, &b); /* some hash type failures */ cl_git_fail(git_odb__hashfile(&a, "status/testfile.txt", 0, GIT_OID_SHA1)); cl_git_fail(git_repository_hashfile(&b, _repo, "testfile.txt", GIT_OBJECT_ANY, NULL)); git_str_dispose(&txt); git_str_dispose(&bin); git_str_dispose(&root); } void test_repo_hashfile__filtered_outside_workdir(void) { git_str root = GIT_STR_INIT, txt = GIT_STR_INIT, bin = GIT_STR_INIT; char cwd[GIT_PATH_MAX]; git_oid a, b; cl_must_pass(p_getcwd(cwd, GIT_PATH_MAX)); cl_must_pass(p_mkdir("absolute", 0777)); cl_git_pass(git_str_joinpath(&root, cwd, "absolute")); cl_git_pass(git_str_joinpath(&txt, root.ptr, "testfile.txt")); cl_git_pass(git_str_joinpath(&bin, root.ptr, "testfile.bin")); cl_repo_set_bool(_repo, "core.autocrlf", true); cl_git_append2file("status/.gitattributes", "*.txt text\n*.bin binary\n\n"); /* create some sample content with CRLF in it */ cl_git_mkfile("absolute/testfile.txt", "content\r\n"); cl_git_mkfile("absolute/testfile.bin", "other\r\nstuff\r\n"); /* not equal hashes because of filtering */ cl_git_pass(git_odb__hashfile(&a, "absolute/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, txt.ptr, GIT_OBJECT_BLOB, "testfile.txt")); cl_assert(git_oid_cmp(&a, &b)); /* equal hashes because filter is binary */ cl_git_pass(git_odb__hashfile(&a, "absolute/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, bin.ptr, GIT_OBJECT_BLOB, "testfile.bin")); cl_assert_equal_oid(&a, &b); /* * equal hashes because no filtering occurs for absolute paths outside the working * directory unless as_path is specified */ cl_git_pass(git_odb__hashfile(&a, "absolute/testfile.txt", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, txt.ptr, GIT_OBJECT_BLOB, NULL)); cl_assert_equal_oid(&a, &b); cl_git_pass(git_odb__hashfile(&a, "absolute/testfile.bin", GIT_OBJECT_BLOB, GIT_OID_SHA1)); cl_git_pass(git_repository_hashfile(&b, _repo, bin.ptr, GIT_OBJECT_BLOB, NULL)); cl_assert_equal_oid(&a, &b); git_str_dispose(&txt); git_str_dispose(&bin); git_str_dispose(&root); }
libgit2-main
tests/libgit2/repo/hashfile.c
#include "clar_libgit2.h" #include "repository.h" #include "repo_helpers.h" #include "posix.h" static git_repository *repo; static git_tree *tree; void test_repo_headtree__initialize(void) { repo = cl_git_sandbox_init("testrepo.git"); tree = NULL; } void test_repo_headtree__cleanup(void) { git_tree_free(tree); cl_git_sandbox_cleanup(); } void test_repo_headtree__can_retrieve_the_root_tree_from_a_detached_head(void) { cl_git_pass(git_repository_detach_head(repo)); cl_git_pass(git_repository_head_tree(&tree, repo)); cl_assert(git_oid_streq(git_tree_id(tree), "az")); } void test_repo_headtree__can_retrieve_the_root_tree_from_a_non_detached_head(void) { cl_assert_equal_i(false, git_repository_head_detached(repo)); cl_git_pass(git_repository_head_tree(&tree, repo)); cl_assert(git_oid_streq(git_tree_id(tree), "az")); } void test_repo_headtree__when_head_is_unborn_returns_EUNBORNBRANCH(void) { make_head_unborn(repo, NON_EXISTING_HEAD); cl_assert_equal_i(true, git_repository_head_unborn(repo)); cl_assert_equal_i(GIT_EUNBORNBRANCH, git_repository_head_tree(&tree, repo)); } void test_repo_headtree__when_head_is_missing_returns_ENOTFOUND(void) { delete_head(repo); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_head_tree(&tree, repo)); }
libgit2-main
tests/libgit2/repo/headtree.c
#include "clar_libgit2.h" #include "refs.h" #include "repo_helpers.h" #include "posix.h" void make_head_unborn(git_repository* repo, const char *target) { git_reference *head; cl_git_pass(git_reference_symbolic_create(&head, repo, GIT_HEAD_FILE, target, 1, NULL)); git_reference_free(head); } void delete_head(git_repository* repo) { git_str head_path = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&head_path, git_repository_path(repo), GIT_HEAD_FILE)); cl_git_pass(p_unlink(git_str_cstr(&head_path))); git_str_dispose(&head_path); } void create_tmp_global_config(const char *dirname, const char *key, const char *val) { git_str path = GIT_STR_INIT; git_config *config; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, dirname)); cl_must_pass(p_mkdir(dirname, 0777)); cl_git_pass(git_str_joinpath(&path, dirname, ".gitconfig")); cl_git_pass(git_config_open_ondisk(&config, path.ptr)); cl_git_pass(git_config_set_string(config, key, val)); git_config_free(config); git_str_dispose(&path); }
libgit2-main
tests/libgit2/repo/repo_helpers.c
#include "clar_libgit2.h" #include "futils.h" #include "sysdir.h" #include <ctype.h> static int validate_ownership = 0; static git_buf config_path = GIT_BUF_INIT; void test_repo_open__initialize(void) { cl_git_pass(git_libgit2_opts(GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &config_path)); cl_git_pass(git_libgit2_opts(GIT_OPT_GET_OWNER_VALIDATION, &validate_ownership)); } void test_repo_open__cleanup(void) { cl_git_sandbox_cleanup(); cl_fixture_cleanup("empty_standard_repo"); cl_fixture_cleanup("testrepo.git"); cl_fixture_cleanup("__global_config"); if (git_fs_path_isdir("alternate")) git_futils_rmdir_r("alternate", NULL, GIT_RMDIR_REMOVE_FILES); git_fs_path__set_owner(GIT_FS_PATH_OWNER_NONE); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, config_path.ptr)); git_buf_dispose(&config_path); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, validate_ownership)); } void test_repo_open__bare_empty_repo(void) { git_repository *repo = cl_git_sandbox_init("empty_bare.git"); cl_assert(git_repository_path(repo) != NULL); cl_assert(git__suffixcmp(git_repository_path(repo), "/") == 0); cl_assert(git_repository_workdir(repo) == NULL); } void test_repo_open__format_version_1(void) { git_repository *repo; git_config *config; repo = cl_git_sandbox_init("empty_bare.git"); cl_git_pass(git_repository_open(&repo, "empty_bare.git")); cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_int32(config, "core.repositoryformatversion", 1)); git_config_free(config); git_repository_free(repo); cl_git_pass(git_repository_open(&repo, "empty_bare.git")); cl_assert(git_repository_path(repo) != NULL); cl_assert(git__suffixcmp(git_repository_path(repo), "/") == 0); git_repository_free(repo); } void test_repo_open__standard_empty_repo_through_gitdir(void) { git_repository *repo; cl_git_pass(git_repository_open(&repo, cl_fixture("empty_standard_repo/.gitted"))); cl_assert(git_repository_path(repo) != NULL); cl_assert(git__suffixcmp(git_repository_path(repo), "/") == 0); cl_assert(git_repository_workdir(repo) != NULL); cl_assert(git__suffixcmp(git_repository_workdir(repo), "/") == 0); git_repository_free(repo); } void test_repo_open__standard_empty_repo_through_workdir(void) { git_repository *repo = cl_git_sandbox_init("empty_standard_repo"); cl_assert(git_repository_path(repo) != NULL); cl_assert(git__suffixcmp(git_repository_path(repo), "/") == 0); cl_assert(git_repository_workdir(repo) != NULL); cl_assert(git__suffixcmp(git_repository_workdir(repo), "/") == 0); } void test_repo_open__open_with_discover(void) { static const char *variants[] = { "attr", "attr/", "attr/.git", "attr/.git/", "attr/sub", "attr/sub/", "attr/sub/sub", "attr/sub/sub/", NULL }; git_repository *repo; const char **scan; cl_fixture_sandbox("attr"); cl_git_pass(p_rename("attr/.gitted", "attr/.git")); for (scan = variants; *scan != NULL; scan++) { cl_git_pass(git_repository_open_ext(&repo, *scan, 0, NULL)); cl_assert(git__suffixcmp(git_repository_path(repo), "attr/.git/") == 0); cl_assert(git__suffixcmp(git_repository_workdir(repo), "attr/") == 0); git_repository_free(repo); } cl_fixture_cleanup("attr"); } void test_repo_open__check_if_repository(void) { cl_git_sandbox_init("empty_standard_repo"); /* Pass NULL for the output parameter to check for but not open the repo */ cl_git_pass(git_repository_open_ext(NULL, "empty_standard_repo", 0, NULL)); cl_git_fail(git_repository_open_ext(NULL, "repo_does_not_exist", 0, NULL)); cl_fixture_cleanup("empty_standard_repo"); } static void make_gitlink_dir(const char *dir, const char *linktext) { git_str path = GIT_STR_INIT; cl_git_pass(git_futils_mkdir(dir, 0777, GIT_MKDIR_VERIFY_DIR)); cl_git_pass(git_str_joinpath(&path, dir, ".git")); cl_git_rewritefile(path.ptr, linktext); git_str_dispose(&path); } void test_repo_open__gitlinked(void) { /* need to have both repo dir and workdir set up correctly */ git_repository *repo = cl_git_sandbox_init("empty_standard_repo"); git_repository *repo2; make_gitlink_dir("alternate", "gitdir: ../empty_standard_repo/.git"); cl_git_pass(git_repository_open(&repo2, "alternate")); cl_assert(git_repository_path(repo2) != NULL); cl_assert_(git__suffixcmp(git_repository_path(repo2), "empty_standard_repo/.git/") == 0, git_repository_path(repo2)); cl_assert_equal_s(git_repository_path(repo), git_repository_path(repo2)); cl_assert(git_repository_workdir(repo2) != NULL); cl_assert_(git__suffixcmp(git_repository_workdir(repo2), "alternate/") == 0, git_repository_workdir(repo2)); git_repository_free(repo2); } void test_repo_open__with_symlinked_config(void) { #ifndef GIT_WIN32 git_str path = GIT_STR_INIT; git_repository *repo; git_config *cfg; int32_t value; cl_git_sandbox_init("empty_standard_repo"); /* Setup .gitconfig as symlink */ cl_git_pass(git_futils_mkdir_r("home", 0777)); cl_git_mkfile("home/.gitconfig.linked", "[global]\ntest = 4567\n"); cl_must_pass(symlink(".gitconfig.linked", "home/.gitconfig")); cl_git_pass(git_fs_path_prettify(&path, "home", NULL)); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); cl_git_pass(git_config_open_default(&cfg)); cl_git_pass(git_config_get_int32(&value, cfg, "global.test")); cl_assert_equal_i(4567, value); git_config_free(cfg); git_repository_free(repo); cl_git_pass(git_futils_rmdir_r(git_str_cstr(&path), NULL, GIT_RMDIR_REMOVE_FILES)); cl_sandbox_set_search_path_defaults(); git_str_dispose(&path); #endif } void test_repo_open__from_git_new_workdir(void) { #ifndef GIT_WIN32 /* The git-new-workdir script that ships with git sets up a bunch of * symlinks to create a second workdir that shares the object db with * another checkout. Libgit2 can open a repo that has been configured * this way. */ git_repository *repo2; git_str link_tgt = GIT_STR_INIT, link = GIT_STR_INIT, body = GIT_STR_INIT; const char **scan; int link_fd; static const char *links[] = { "config", "refs", "logs/refs", "objects", "info", "hooks", "packed-refs", "remotes", "rr-cache", "svn", NULL }; static const char *copies[] = { "HEAD", NULL }; cl_git_sandbox_init("empty_standard_repo"); cl_git_pass(p_mkdir("alternate", 0777)); cl_git_pass(p_mkdir("alternate/.git", 0777)); for (scan = links; *scan != NULL; scan++) { git_str_joinpath(&link_tgt, "empty_standard_repo/.git", *scan); if (git_fs_path_exists(link_tgt.ptr)) { git_str_joinpath(&link_tgt, "../../empty_standard_repo/.git", *scan); git_str_joinpath(&link, "alternate/.git", *scan); if (strchr(*scan, '/')) git_futils_mkpath2file(link.ptr, 0777); cl_assert_(symlink(link_tgt.ptr, link.ptr) == 0, strerror(errno)); } } for (scan = copies; *scan != NULL; scan++) { git_str_joinpath(&link_tgt, "empty_standard_repo/.git", *scan); if (git_fs_path_exists(link_tgt.ptr)) { git_str_joinpath(&link, "alternate/.git", *scan); cl_git_pass(git_futils_readbuffer(&body, link_tgt.ptr)); cl_assert((link_fd = git_futils_creat_withpath(link.ptr, 0777, 0666)) >= 0); cl_must_pass(p_write(link_fd, body.ptr, body.size)); p_close(link_fd); } } git_str_dispose(&link_tgt); git_str_dispose(&link); git_str_dispose(&body); cl_git_pass(git_repository_open(&repo2, "alternate")); cl_assert(git_repository_path(repo2) != NULL); cl_assert_(git__suffixcmp(git_repository_path(repo2), "alternate/.git/") == 0, git_repository_path(repo2)); cl_assert(git_repository_workdir(repo2) != NULL); cl_assert_(git__suffixcmp(git_repository_workdir(repo2), "alternate/") == 0, git_repository_workdir(repo2)); git_repository_free(repo2); #else cl_skip(); #endif } void test_repo_open__failures(void) { git_repository *base, *repo; git_str ceiling = GIT_STR_INIT; base = cl_git_sandbox_init("attr"); cl_git_pass(git_str_sets(&ceiling, git_repository_workdir(base))); /* fail with no searching */ cl_git_fail(git_repository_open(&repo, "attr/sub")); cl_git_fail(git_repository_open_ext( &repo, "attr/sub", GIT_REPOSITORY_OPEN_NO_SEARCH, NULL)); /* fail with ceiling too low */ cl_git_fail(git_repository_open_ext(&repo, "attr/sub", 0, ceiling.ptr)); cl_git_pass(git_str_joinpath(&ceiling, ceiling.ptr, "sub")); cl_git_fail(git_repository_open_ext(&repo, "attr/sub/sub", 0, ceiling.ptr)); /* fail with no repo */ cl_git_pass(p_mkdir("alternate", 0777)); cl_git_pass(p_mkdir("alternate/.git", 0777)); cl_git_fail(git_repository_open_ext(&repo, "alternate", 0, NULL)); cl_git_fail(git_repository_open_ext(&repo, "alternate/.git", 0, NULL)); /* fail with no searching and no appending .git */ cl_git_fail(git_repository_open_ext( &repo, "attr", GIT_REPOSITORY_OPEN_NO_SEARCH | GIT_REPOSITORY_OPEN_NO_DOTGIT, NULL)); git_str_dispose(&ceiling); } void test_repo_open__bad_gitlinks(void) { git_repository *repo; static const char *bad_links[] = { "garbage\n", "gitdir", "gitdir:\n", "gitdir: foobar", "gitdir: ../invalid", "gitdir: ../invalid2", "gitdir: ../attr/.git with extra stuff", NULL }; const char **scan; cl_git_sandbox_init("attr"); cl_git_pass(p_mkdir("invalid", 0777)); cl_git_pass(git_futils_mkdir_r("invalid2/.git", 0777)); for (scan = bad_links; *scan != NULL; scan++) { make_gitlink_dir("alternate", *scan); repo = NULL; cl_git_fail(git_repository_open_ext(&repo, "alternate", 0, NULL)); cl_assert(repo == NULL); } git_futils_rmdir_r("invalid", NULL, GIT_RMDIR_REMOVE_FILES); git_futils_rmdir_r("invalid2", NULL, GIT_RMDIR_REMOVE_FILES); } #ifdef GIT_WIN32 static void unposix_path(git_str *path) { char *src, *tgt; src = tgt = path->ptr; /* convert "/d/..." to "d:\..." */ if (src[0] == '/' && isalpha(src[1]) && src[2] == '/') { *tgt++ = src[1]; *tgt++ = ':'; *tgt++ = '\\'; src += 3; } while (*src) { *tgt++ = (*src == '/') ? '\\' : *src; src++; } *tgt = '\0'; } #endif void test_repo_open__win32_path(void) { #ifdef GIT_WIN32 git_repository *repo = cl_git_sandbox_init("empty_standard_repo"), *repo2; git_str winpath = GIT_STR_INIT; static const char *repo_path = "empty_standard_repo/.git/"; static const char *repo_wd = "empty_standard_repo/"; cl_assert(git__suffixcmp(git_repository_path(repo), repo_path) == 0); cl_assert(git__suffixcmp(git_repository_workdir(repo), repo_wd) == 0); cl_git_pass(git_str_sets(&winpath, git_repository_path(repo))); unposix_path(&winpath); cl_git_pass(git_repository_open(&repo2, winpath.ptr)); cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0); cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0); git_repository_free(repo2); cl_git_pass(git_str_sets(&winpath, git_repository_path(repo))); git_str_truncate(&winpath, winpath.size - 1); /* remove trailing '/' */ unposix_path(&winpath); cl_git_pass(git_repository_open(&repo2, winpath.ptr)); cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0); cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0); git_repository_free(repo2); cl_git_pass(git_str_sets(&winpath, git_repository_workdir(repo))); unposix_path(&winpath); cl_git_pass(git_repository_open(&repo2, winpath.ptr)); cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0); cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0); git_repository_free(repo2); cl_git_pass(git_str_sets(&winpath, git_repository_workdir(repo))); git_str_truncate(&winpath, winpath.size - 1); /* remove trailing '/' */ unposix_path(&winpath); cl_git_pass(git_repository_open(&repo2, winpath.ptr)); cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0); cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0); git_repository_free(repo2); git_str_dispose(&winpath); #endif } void test_repo_open__opening_a_non_existing_repository_returns_ENOTFOUND(void) { git_repository *repo; cl_assert_equal_i(GIT_ENOTFOUND, git_repository_open(&repo, "i-do-not/exist")); } void test_repo_open__no_config(void) { git_str path = GIT_STR_INIT; git_repository *repo; git_config *config; cl_fixture_sandbox("empty_standard_repo"); cl_git_pass(cl_rename( "empty_standard_repo/.gitted", "empty_standard_repo/.git")); /* remove local config */ cl_git_pass(git_futils_rmdir_r( "empty_standard_repo/.git/config", NULL, GIT_RMDIR_REMOVE_FILES)); /* isolate from system level configs */ cl_must_pass(p_mkdir("alternate", 0777)); cl_git_pass(git_fs_path_prettify(&path, "alternate", NULL)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr)); git_str_dispose(&path); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_string(config, "test.set", "42")); git_config_free(config); git_repository_free(repo); cl_fixture_cleanup("empty_standard_repo"); cl_sandbox_set_search_path_defaults(); } void test_repo_open__force_bare(void) { /* need to have both repo dir and workdir set up correctly */ git_repository *repo = cl_git_sandbox_init("empty_standard_repo"); git_repository *barerepo; make_gitlink_dir("alternate", "gitdir: ../empty_standard_repo/.git"); cl_assert(!git_repository_is_bare(repo)); cl_git_pass(git_repository_open(&barerepo, "alternate")); cl_assert(!git_repository_is_bare(barerepo)); git_repository_free(barerepo); cl_git_pass(git_repository_open_bare( &barerepo, "empty_standard_repo/.git")); cl_assert(git_repository_is_bare(barerepo)); git_repository_free(barerepo); cl_git_fail(git_repository_open_bare(&barerepo, "alternate/.git")); cl_git_pass(git_repository_open_ext( &barerepo, "alternate/.git", GIT_REPOSITORY_OPEN_BARE, NULL)); cl_assert(git_repository_is_bare(barerepo)); git_repository_free(barerepo); cl_git_pass(p_mkdir("empty_standard_repo/subdir", 0777)); cl_git_mkfile("empty_standard_repo/subdir/something.txt", "something"); cl_git_fail(git_repository_open_bare( &barerepo, "empty_standard_repo/subdir")); cl_git_pass(git_repository_open_ext( &barerepo, "empty_standard_repo/subdir", GIT_REPOSITORY_OPEN_BARE, NULL)); cl_assert(git_repository_is_bare(barerepo)); git_repository_free(barerepo); cl_git_pass(p_mkdir("alternate/subdir", 0777)); cl_git_pass(p_mkdir("alternate/subdir/sub2", 0777)); cl_git_mkfile("alternate/subdir/sub2/something.txt", "something"); cl_git_fail(git_repository_open_bare(&barerepo, "alternate/subdir/sub2")); cl_git_pass(git_repository_open_ext( &barerepo, "alternate/subdir/sub2", GIT_REPOSITORY_OPEN_BARE|GIT_REPOSITORY_OPEN_CROSS_FS, NULL)); cl_assert(git_repository_is_bare(barerepo)); git_repository_free(barerepo); } void test_repo_open__validates_dir_ownership(void) { git_repository *repo; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 1)); cl_fixture_sandbox("empty_standard_repo"); cl_git_pass(cl_rename("empty_standard_repo/.gitted", "empty_standard_repo/.git")); /* When the current user owns the repo config, that's acceptable */ git_fs_path__set_owner(GIT_FS_PATH_OWNER_CURRENT_USER); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository_free(repo); /* When the system user owns the repo config, fail */ git_fs_path__set_owner(GIT_FS_PATH_OWNER_ADMINISTRATOR); cl_git_fail(git_repository_open(&repo, "empty_standard_repo")); #ifdef GIT_WIN32 /* When the user is an administrator, succeed on Windows. */ git_fs_path__set_owner(GIT_FS_PATH_USER_IS_ADMINISTRATOR); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository_free(repo); #endif /* When an unknown user owns the repo config, fail */ git_fs_path__set_owner(GIT_FS_PATH_OWNER_OTHER); cl_git_fail(git_repository_open(&repo, "empty_standard_repo")); } void test_repo_open__validates_bare_repo_ownership(void) { git_repository *repo; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 1)); cl_fixture_sandbox("testrepo.git"); /* When the current user owns the repo config, that's acceptable */ git_fs_path__set_owner(GIT_FS_PATH_OWNER_CURRENT_USER); cl_git_pass(git_repository_open(&repo, "testrepo.git")); git_repository_free(repo); /* When the system user owns the repo config, fail */ git_fs_path__set_owner(GIT_FS_PATH_OWNER_ADMINISTRATOR); cl_git_fail(git_repository_open(&repo, "testrepo.git")); #ifdef GIT_WIN32 /* When the user is an administrator, succeed on Windows. */ git_fs_path__set_owner(GIT_FS_PATH_USER_IS_ADMINISTRATOR); cl_git_pass(git_repository_open(&repo, "testrepo.git")); git_repository_free(repo); #endif /* When an unknown user owns the repo config, fail */ git_fs_path__set_owner(GIT_FS_PATH_OWNER_OTHER); cl_git_fail(git_repository_open(&repo, "testrepo.git")); } void test_repo_open__can_allowlist_dirs_with_problematic_ownership(void) { git_repository *repo; git_str config_path = GIT_STR_INIT, config_filename = GIT_STR_INIT, config_data = GIT_STR_INIT; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 1)); cl_fixture_sandbox("empty_standard_repo"); cl_git_pass(cl_rename("empty_standard_repo/.gitted", "empty_standard_repo/.git")); git_fs_path__set_owner(GIT_FS_PATH_OWNER_OTHER); cl_git_fail(git_repository_open(&repo, "empty_standard_repo")); /* Add safe.directory options to the global configuration */ git_str_joinpath(&config_path, clar_sandbox_path(), "__global_config"); cl_must_pass(p_mkdir(config_path.ptr, 0777)); git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, config_path.ptr); git_str_joinpath(&config_filename, config_path.ptr, ".gitconfig"); git_str_printf(&config_data, "[foo]\n" \ "\tbar = Foobar\n" \ "\tbaz = Baz!\n" \ "[safe]\n" \ "\tdirectory = /non/existent/path\n" \ "\tdirectory = /\n" \ "\tdirectory = c:\\\\temp\n" \ "\tdirectory = %s/%s\n" \ "\tdirectory = /tmp\n" \ "[bar]\n" \ "\tfoo = barfoo\n", clar_sandbox_path(), "empty_standard_repo"); cl_git_rewritefile(config_filename.ptr, config_data.ptr); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository_free(repo); git_str_dispose(&config_path); git_str_dispose(&config_filename); git_str_dispose(&config_data); } void test_repo_open__can_allowlist_bare_gitdir(void) { git_repository *repo; git_str config_path = GIT_STR_INIT, config_filename = GIT_STR_INIT, config_data = GIT_STR_INIT; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 1)); cl_fixture_sandbox("testrepo.git"); git_fs_path__set_owner(GIT_FS_PATH_OWNER_OTHER); cl_git_fail(git_repository_open(&repo, "testrepo.git")); /* Add safe.directory options to the global configuration */ git_str_joinpath(&config_path, clar_sandbox_path(), "__global_config"); cl_must_pass(p_mkdir(config_path.ptr, 0777)); git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, config_path.ptr); git_str_joinpath(&config_filename, config_path.ptr, ".gitconfig"); git_str_printf(&config_data, "[foo]\n" \ "\tbar = Foobar\n" \ "\tbaz = Baz!\n" \ "[safe]\n" \ "\tdirectory = /non/existent/path\n" \ "\tdirectory = /\n" \ "\tdirectory = c:\\\\temp\n" \ "\tdirectory = %s/%s\n" \ "\tdirectory = /tmp\n" \ "[bar]\n" \ "\tfoo = barfoo\n", clar_sandbox_path(), "testrepo.git"); cl_git_rewritefile(config_filename.ptr, config_data.ptr); cl_git_pass(git_repository_open(&repo, "testrepo.git")); git_repository_free(repo); git_str_dispose(&config_path); git_str_dispose(&config_filename); git_str_dispose(&config_data); } void test_repo_open__can_reset_safe_directory_list(void) { git_repository *repo; git_str config_path = GIT_STR_INIT, config_filename = GIT_STR_INIT, config_data = GIT_STR_INIT; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 1)); cl_fixture_sandbox("empty_standard_repo"); cl_git_pass(cl_rename("empty_standard_repo/.gitted", "empty_standard_repo/.git")); git_fs_path__set_owner(GIT_FS_PATH_OWNER_OTHER); cl_git_fail(git_repository_open(&repo, "empty_standard_repo")); /* Add safe.directory options to the global configuration */ git_str_joinpath(&config_path, clar_sandbox_path(), "__global_config"); cl_must_pass(p_mkdir(config_path.ptr, 0777)); git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, config_path.ptr); git_str_joinpath(&config_filename, config_path.ptr, ".gitconfig"); /* The blank resets our sandbox directory and opening fails */ git_str_printf(&config_data, "[foo]\n" \ "\tbar = Foobar\n" \ "\tbaz = Baz!\n" \ "[safe]\n" \ "\tdirectory = %s/%s\n" \ "\tdirectory = \n" \ "\tdirectory = /tmp\n" \ "[bar]\n" \ "\tfoo = barfoo\n", clar_sandbox_path(), "empty_standard_repo"); cl_git_rewritefile(config_filename.ptr, config_data.ptr); cl_git_fail(git_repository_open(&repo, "empty_standard_repo")); /* The blank resets tmp and allows subsequent declarations to succeed */ git_str_clear(&config_data); git_str_printf(&config_data, "[foo]\n" \ "\tbar = Foobar\n" \ "\tbaz = Baz!\n" \ "[safe]\n" \ "\tdirectory = /tmp\n" \ "\tdirectory = \n" \ "\tdirectory = %s/%s\n" \ "[bar]\n" \ "\tfoo = barfoo\n", clar_sandbox_path(), "empty_standard_repo"); cl_git_rewritefile(config_filename.ptr, config_data.ptr); cl_git_pass(git_repository_open(&repo, "empty_standard_repo")); git_repository_free(repo); git_str_dispose(&config_path); git_str_dispose(&config_filename); git_str_dispose(&config_data); }
libgit2-main
tests/libgit2/repo/open.c
#include "clar_libgit2.h" #include "refs.h" #include "posix.h" static git_repository *_repo; void test_repo_message__initialize(void) { _repo = cl_git_sandbox_init("testrepo.git"); } void test_repo_message__cleanup(void) { cl_git_sandbox_cleanup(); } void test_repo_message__none(void) { git_buf actual = GIT_BUF_INIT; cl_assert_equal_i(GIT_ENOTFOUND, git_repository_message(&actual, _repo)); } void test_repo_message__message(void) { git_str path = GIT_STR_INIT; git_buf actual = GIT_BUF_INIT; const char expected[] = "Test\n\nThis is a test of the emergency broadcast system\n"; cl_git_pass(git_str_joinpath(&path, git_repository_path(_repo), "MERGE_MSG")); cl_git_mkfile(git_str_cstr(&path), expected); cl_git_pass(git_repository_message(&actual, _repo)); cl_assert_equal_s(expected, actual.ptr); git_buf_dispose(&actual); cl_git_pass(p_unlink(git_str_cstr(&path))); cl_assert_equal_i(GIT_ENOTFOUND, git_repository_message(&actual, _repo)); git_str_dispose(&path); }
libgit2-main
tests/libgit2/repo/message.c
#include "clar_libgit2.h" #include "git2/sys/repository.h" void test_repo_new__has_nothing(void) { git_repository *repo; cl_git_pass(git_repository_new(&repo)); cl_assert_equal_b(true, git_repository_is_bare(repo)); cl_assert_equal_p(NULL, git_repository_path(repo)); cl_assert_equal_p(NULL, git_repository_workdir(repo)); git_repository_free(repo); } void test_repo_new__is_bare_until_workdir_set(void) { git_repository *repo; cl_git_pass(git_repository_new(&repo)); cl_assert_equal_b(true, git_repository_is_bare(repo)); cl_git_pass(git_repository_set_workdir(repo, clar_sandbox_path(), 0)); cl_assert_equal_b(false, git_repository_is_bare(repo)); git_repository_free(repo); }
libgit2-main
tests/libgit2/repo/new.c
#include "clar_libgit2.h" #include "git2/pathspec.h" static git_repository *g_repo; void test_repo_pathspec__initialize(void) { g_repo = cl_git_sandbox_init("status"); } void test_repo_pathspec__cleanup(void) { cl_git_sandbox_cleanup(); g_repo = NULL; } static char *str0[] = { "*_file", "new_file", "garbage" }; static char *str1[] = { "*_FILE", "NEW_FILE", "GARBAGE" }; static char *str2[] = { "staged_*" }; static char *str3[] = { "!subdir", "*_file", "new_file" }; static char *str4[] = { "*" }; static char *str5[] = { "S*" }; void test_repo_pathspec__workdir0(void) { git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "*_file", "new_file", "garbage" } */ s.strings = str0; s.count = ARRAY_SIZE(str0); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, 0, ps)); cl_assert_equal_sz(10, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(10, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(1, git_pathspec_match_list_failed_entrycount(m)); cl_assert_equal_s("garbage", git_pathspec_match_list_failed_entry(m, 0)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_FIND_FAILURES | GIT_PATHSPEC_FAILURES_ONLY, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(1, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); git_pathspec_free(ps); } void test_repo_pathspec__workdir1(void) { git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "*_FILE", "NEW_FILE", "GARBAGE" } */ s.strings = str1; s.count = ARRAY_SIZE(str1); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_IGNORE_CASE, ps)); cl_assert_equal_sz(10, git_pathspec_match_list_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_USE_CASE, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); git_pathspec_match_list_free(m); cl_git_fail(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_USE_CASE | GIT_PATHSPEC_NO_MATCH_ERROR, ps)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_IGNORE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(10, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(1, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_USE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(3, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); git_pathspec_free(ps); } void test_repo_pathspec__workdir2(void) { git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "staged_*" } */ s.strings = str2; s.count = ARRAY_SIZE(str2); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, 0, ps)); cl_assert_equal_sz(5, git_pathspec_match_list_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(5, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); cl_git_fail(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_NO_GLOB | GIT_PATHSPEC_NO_MATCH_ERROR, ps)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_NO_GLOB | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(1, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); git_pathspec_free(ps); } void test_repo_pathspec__workdir3(void) { git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "!subdir", "*_file", "new_file" } */ s.strings = str3; s.count = ARRAY_SIZE(str3); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, 0, ps)); cl_assert_equal_sz(7, git_pathspec_match_list_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(7, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); cl_assert_equal_s("current_file", git_pathspec_match_list_entry(m, 0)); cl_assert_equal_s("modified_file", git_pathspec_match_list_entry(m, 1)); cl_assert_equal_s("new_file", git_pathspec_match_list_entry(m, 2)); cl_assert_equal_s("staged_changes_modified_file", git_pathspec_match_list_entry(m, 3)); cl_assert_equal_s("staged_delete_modified_file", git_pathspec_match_list_entry(m, 4)); cl_assert_equal_s("staged_new_file", git_pathspec_match_list_entry(m, 5)); cl_assert_equal_s("staged_new_file_modified_file", git_pathspec_match_list_entry(m, 6)); cl_assert_equal_s(NULL, git_pathspec_match_list_entry(m, 7)); git_pathspec_match_list_free(m); git_pathspec_free(ps); } void test_repo_pathspec__workdir4(void) { git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "*" } */ s.strings = str4; s.count = ARRAY_SIZE(str4); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_workdir(&m, g_repo, 0, ps)); cl_assert_equal_sz(13, git_pathspec_match_list_entrycount(m)); cl_assert_equal_s("\xE8\xBF\x99", git_pathspec_match_list_entry(m, 12)); git_pathspec_match_list_free(m); git_pathspec_free(ps); } void test_repo_pathspec__index0(void) { git_index *idx; git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; cl_git_pass(git_repository_index(&idx, g_repo)); /* { "*_file", "new_file", "garbage" } */ s.strings = str0; s.count = ARRAY_SIZE(str0); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_index(&m, idx, 0, ps)); cl_assert_equal_sz(9, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); cl_assert_equal_s("current_file", git_pathspec_match_list_entry(m, 0)); cl_assert_equal_s("modified_file", git_pathspec_match_list_entry(m, 1)); cl_assert_equal_s("staged_changes_modified_file", git_pathspec_match_list_entry(m, 2)); cl_assert_equal_s("staged_new_file", git_pathspec_match_list_entry(m, 3)); cl_assert_equal_s("staged_new_file_deleted_file", git_pathspec_match_list_entry(m, 4)); cl_assert_equal_s("staged_new_file_modified_file", git_pathspec_match_list_entry(m, 5)); cl_assert_equal_s("subdir/current_file", git_pathspec_match_list_entry(m, 6)); cl_assert_equal_s("subdir/deleted_file", git_pathspec_match_list_entry(m, 7)); cl_assert_equal_s("subdir/modified_file", git_pathspec_match_list_entry(m, 8)); cl_assert_equal_s(NULL, git_pathspec_match_list_entry(m, 9)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_index(&m, idx, GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(9, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(2, git_pathspec_match_list_failed_entrycount(m)); cl_assert_equal_s("new_file", git_pathspec_match_list_failed_entry(m, 0)); cl_assert_equal_s("garbage", git_pathspec_match_list_failed_entry(m, 1)); cl_assert_equal_s(NULL, git_pathspec_match_list_failed_entry(m, 2)); git_pathspec_match_list_free(m); git_pathspec_free(ps); git_index_free(idx); } void test_repo_pathspec__index1(void) { /* Currently the USE_CASE and IGNORE_CASE flags don't work on the * index because the index sort order for the index iterator is * set by the index itself. I think the correct fix is for the * index not to embed a global sort order but to support traversal * in either case sensitive or insensitive order in a stateless * manner. * * Anyhow, as it is, there is no point in doing this test. */ #if 0 git_index *idx; git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; cl_git_pass(git_repository_index(&idx, g_repo)); /* { "*_FILE", "NEW_FILE", "GARBAGE" } */ s.strings = str1; s.count = ARRAY_SIZE(str1); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_pathspec_match_index(&m, idx, GIT_PATHSPEC_USE_CASE, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_index(&m, idx, GIT_PATHSPEC_USE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(3, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_index(&m, idx, GIT_PATHSPEC_IGNORE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(10, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(2, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); git_pathspec_free(ps); git_index_free(idx); #endif } void test_repo_pathspec__tree0(void) { git_object *tree; git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "*_file", "new_file", "garbage" } */ s.strings = str0; s.count = ARRAY_SIZE(str0); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_revparse_single(&tree, g_repo, "HEAD~2^{tree}")); cl_git_pass(git_pathspec_match_tree(&m, (git_tree *)tree, GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(4, git_pathspec_match_list_entrycount(m)); cl_assert_equal_s("current_file", git_pathspec_match_list_entry(m, 0)); cl_assert_equal_s("modified_file", git_pathspec_match_list_entry(m, 1)); cl_assert_equal_s("staged_changes_modified_file", git_pathspec_match_list_entry(m, 2)); cl_assert_equal_s("staged_delete_modified_file", git_pathspec_match_list_entry(m, 3)); cl_assert_equal_s(NULL, git_pathspec_match_list_entry(m, 4)); cl_assert_equal_sz(2, git_pathspec_match_list_failed_entrycount(m)); cl_assert_equal_s("new_file", git_pathspec_match_list_failed_entry(m, 0)); cl_assert_equal_s("garbage", git_pathspec_match_list_failed_entry(m, 1)); cl_assert_equal_s(NULL, git_pathspec_match_list_failed_entry(m, 2)); git_pathspec_match_list_free(m); git_object_free(tree); cl_git_pass(git_revparse_single(&tree, g_repo, "HEAD^{tree}")); cl_git_pass(git_pathspec_match_tree(&m, (git_tree *)tree, GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(7, git_pathspec_match_list_entrycount(m)); cl_assert_equal_s("current_file", git_pathspec_match_list_entry(m, 0)); cl_assert_equal_s("modified_file", git_pathspec_match_list_entry(m, 1)); cl_assert_equal_s("staged_changes_modified_file", git_pathspec_match_list_entry(m, 2)); cl_assert_equal_s("staged_delete_modified_file", git_pathspec_match_list_entry(m, 3)); cl_assert_equal_s("subdir/current_file", git_pathspec_match_list_entry(m, 4)); cl_assert_equal_s("subdir/deleted_file", git_pathspec_match_list_entry(m, 5)); cl_assert_equal_s("subdir/modified_file", git_pathspec_match_list_entry(m, 6)); cl_assert_equal_s(NULL, git_pathspec_match_list_entry(m, 7)); cl_assert_equal_sz(2, git_pathspec_match_list_failed_entrycount(m)); cl_assert_equal_s("new_file", git_pathspec_match_list_failed_entry(m, 0)); cl_assert_equal_s("garbage", git_pathspec_match_list_failed_entry(m, 1)); cl_assert_equal_s(NULL, git_pathspec_match_list_failed_entry(m, 2)); git_pathspec_match_list_free(m); git_object_free(tree); git_pathspec_free(ps); } void test_repo_pathspec__tree5(void) { git_object *tree; git_strarray s; git_pathspec *ps; git_pathspec_match_list *m; /* { "S*" } */ s.strings = str5; s.count = ARRAY_SIZE(str5); cl_git_pass(git_pathspec_new(&ps, &s)); cl_git_pass(git_revparse_single(&tree, g_repo, "HEAD~2^{tree}")); cl_git_pass(git_pathspec_match_tree(&m, (git_tree *)tree, GIT_PATHSPEC_USE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(0, git_pathspec_match_list_entrycount(m)); cl_assert_equal_sz(1, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); cl_git_pass(git_pathspec_match_tree(&m, (git_tree *)tree, GIT_PATHSPEC_IGNORE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(5, git_pathspec_match_list_entrycount(m)); cl_assert_equal_s("staged_changes", git_pathspec_match_list_entry(m, 0)); cl_assert_equal_s("staged_delete_modified_file", git_pathspec_match_list_entry(m, 4)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); git_object_free(tree); cl_git_pass(git_revparse_single(&tree, g_repo, "HEAD^{tree}")); cl_git_pass(git_pathspec_match_tree(&m, (git_tree *)tree, GIT_PATHSPEC_IGNORE_CASE | GIT_PATHSPEC_FIND_FAILURES, ps)); cl_assert_equal_sz(9, git_pathspec_match_list_entrycount(m)); cl_assert_equal_s("staged_changes", git_pathspec_match_list_entry(m, 0)); cl_assert_equal_s("subdir.txt", git_pathspec_match_list_entry(m, 5)); cl_assert_equal_s("subdir/current_file", git_pathspec_match_list_entry(m, 6)); cl_assert_equal_sz(0, git_pathspec_match_list_failed_entrycount(m)); git_pathspec_match_list_free(m); git_object_free(tree); git_pathspec_free(ps); } void test_repo_pathspec__in_memory(void) { static char *strings[] = { "one", "two*", "!three*", "*four" }; git_strarray s = { strings, ARRAY_SIZE(strings) }; git_pathspec *ps; cl_git_pass(git_pathspec_new(&ps, &s)); cl_assert(git_pathspec_matches_path(ps, 0, "one")); cl_assert(!git_pathspec_matches_path(ps, 0, "ONE")); cl_assert(git_pathspec_matches_path(ps, GIT_PATHSPEC_IGNORE_CASE, "ONE")); cl_assert(git_pathspec_matches_path(ps, 0, "two")); cl_assert(git_pathspec_matches_path(ps, 0, "two.txt")); cl_assert(!git_pathspec_matches_path(ps, 0, "three.txt")); cl_assert(git_pathspec_matches_path(ps, 0, "anything.four")); cl_assert(!git_pathspec_matches_path(ps, 0, "three.four")); cl_assert(!git_pathspec_matches_path(ps, 0, "nomatch")); cl_assert(!git_pathspec_matches_path(ps, GIT_PATHSPEC_NO_GLOB, "two")); cl_assert(git_pathspec_matches_path(ps, GIT_PATHSPEC_NO_GLOB, "two*")); cl_assert(!git_pathspec_matches_path(ps, GIT_PATHSPEC_NO_GLOB, "anyfour")); cl_assert(git_pathspec_matches_path(ps, GIT_PATHSPEC_NO_GLOB, "*four")); git_pathspec_free(ps); }
libgit2-main
tests/libgit2/repo/pathspec.c
#include "clar.h" #include "clar_libgit2.h" #include "diff_generate.h" static git_repository *repo; void test_email_create__initialize(void) { repo = cl_git_sandbox_init("diff_format_email"); } void test_email_create__cleanup(void) { cl_git_sandbox_cleanup(); } static void email_for_commit( git_buf *out, const char *commit_id, git_email_create_options *opts) { git_oid oid; git_commit *commit = NULL; git_diff *diff = NULL; git_oid__fromstr(&oid, commit_id, GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_email_create_from_commit(out, commit, opts)); git_diff_free(diff); git_commit_free(commit); } static void assert_email_match( const char *expected, const char *commit_id, git_email_create_options *opts) { git_buf buf = GIT_BUF_INIT; email_for_commit(&buf, commit_id, opts); cl_assert_equal_s(expected, buf.ptr); git_buf_dispose(&buf); } static void assert_subject_match( const char *expected, const char *commit_id, git_email_create_options *opts) { git_buf buf = GIT_BUF_INIT; char *subject, *nl; email_for_commit(&buf, commit_id, opts); cl_assert((subject = strstr(buf.ptr, "\nSubject: ")) != NULL); subject += 10; if ((nl = strchr(subject, '\n')) != NULL) *nl = '\0'; cl_assert_equal_s(expected, subject); git_buf_dispose(&buf); } void test_email_create__commit(void) { const char *expected = "From 9264b96c6d104d0e07ae33d3007b6a48246c6f92 Mon Sep 17 00:00:00 2001\n" \ "From: Jacques Germishuys <[email protected]>\n" \ "Date: Wed, 9 Apr 2014 20:57:01 +0200\n" \ "Subject: [PATCH] Modify some content\n" \ "\n" \ "---\n" \ " file1.txt | 8 +++++---\n" \ " 1 file changed, 5 insertions(+), 3 deletions(-)\n" \ "\n" \ "diff --git a/file1.txt b/file1.txt\n" \ "index 94aaae8..af8f41d 100644\n" \ "--- a/file1.txt\n" \ "+++ b/file1.txt\n" \ "@@ -1,15 +1,17 @@\n" \ " file1.txt\n" \ " file1.txt\n" \ "+_file1.txt_\n" \ " file1.txt\n" \ " file1.txt\n" \ " file1.txt\n" \ " file1.txt\n" \ "+\n" \ "+\n" \ " file1.txt\n" \ " file1.txt\n" \ " file1.txt\n" \ " file1.txt\n" \ " file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "+_file1.txt_\n" \ "+_file1.txt_\n" \ " file1.txt\n" \ "--\n" \ "libgit2 " LIBGIT2_VERSION "\n" \ "\n"; assert_email_match( expected, "9264b96c6d104d0e07ae33d3007b6a48246c6f92", NULL); } void test_email_create__rename(void) { const char *expected = "From 6e05acc5a5dab507d91a0a0cc0fb05a3dd98892d Mon Sep 17 00:00:00 2001\n" \ "From: Jacques Germishuys <[email protected]>\n" \ "Date: Wed, 9 Apr 2014 21:15:56 +0200\n" \ "Subject: [PATCH] Renamed file1.txt -> file1.txt.renamed\n" \ "\n" \ "---\n" \ " file1.txt => file1.txt.renamed | 4 ++--\n" \ " 1 file changed, 2 insertions(+), 2 deletions(-)\n" \ "\n" \ "diff --git a/file1.txt b/file1.txt.renamed\n" \ "similarity index 86%\n" \ "rename from file1.txt\n" \ "rename to file1.txt.renamed\n" \ "index af8f41d..a97157a 100644\n" \ "--- a/file1.txt\n" \ "+++ b/file1.txt.renamed\n" \ "@@ -3,13 +3,13 @@ file1.txt\n" \ " _file1.txt_\n" \ " file1.txt\n" \ " file1.txt\n" \ "-file1.txt\n" \ "+file1.txt_renamed\n" \ " file1.txt\n" \ " \n" \ " \n" \ " file1.txt\n" \ " file1.txt\n" \ "-file1.txt\n" \ "+file1.txt_renamed\n" \ " file1.txt\n" \ " file1.txt\n" \ " _file1.txt_\n" \ "--\n" \ "libgit2 " LIBGIT2_VERSION "\n" \ "\n"; assert_email_match(expected, "6e05acc5a5dab507d91a0a0cc0fb05a3dd98892d", NULL); } void test_email_create__rename_as_add_delete(void) { const char *expected = "From 6e05acc5a5dab507d91a0a0cc0fb05a3dd98892d Mon Sep 17 00:00:00 2001\n" \ "From: Jacques Germishuys <[email protected]>\n" \ "Date: Wed, 9 Apr 2014 21:15:56 +0200\n" \ "Subject: [PATCH] Renamed file1.txt -> file1.txt.renamed\n" \ "\n" \ "---\n" \ " file1.txt | 17 -----------------\n" \ " file1.txt.renamed | 17 +++++++++++++++++\n" \ " 2 files changed, 17 insertions(+), 17 deletions(-)\n" \ " delete mode 100644 file1.txt\n" \ " create mode 100644 file1.txt.renamed\n" \ "\n" \ "diff --git a/file1.txt b/file1.txt\n" \ "deleted file mode 100644\n" \ "index af8f41d..0000000\n" \ "--- a/file1.txt\n" \ "+++ /dev/null\n" \ "@@ -1,17 +0,0 @@\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-_file1.txt_\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-\n" \ "-\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-file1.txt\n" \ "-_file1.txt_\n" \ "-_file1.txt_\n" \ "-file1.txt\n" \ "diff --git a/file1.txt.renamed b/file1.txt.renamed\n" \ "new file mode 100644\n" \ "index 0000000..a97157a\n" \ "--- /dev/null\n" \ "+++ b/file1.txt.renamed\n" \ "@@ -0,0 +1,17 @@\n" \ "+file1.txt\n" \ "+file1.txt\n" \ "+_file1.txt_\n" \ "+file1.txt\n" \ "+file1.txt\n" \ "+file1.txt_renamed\n" \ "+file1.txt\n" \ "+\n" \ "+\n" \ "+file1.txt\n" \ "+file1.txt\n" \ "+file1.txt_renamed\n" \ "+file1.txt\n" \ "+file1.txt\n" \ "+_file1.txt_\n" \ "+_file1.txt_\n" \ "+file1.txt\n" \ "--\n" \ "libgit2 " LIBGIT2_VERSION "\n" \ "\n"; git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT; opts.flags |= GIT_EMAIL_CREATE_NO_RENAMES; assert_email_match(expected, "6e05acc5a5dab507d91a0a0cc0fb05a3dd98892d", &opts); } void test_email_create__binary(void) { const char *expected = "From 8d7523f6fcb2404257889abe0d96f093d9f524f9 Mon Sep 17 00:00:00 2001\n" \ "From: Jacques Germishuys <[email protected]>\n" \ "Date: Sun, 13 Apr 2014 18:10:18 +0200\n" \ "Subject: [PATCH] Modified binary file\n" \ "\n" \ "---\n" \ " binary.bin | Bin 3 -> 5 bytes\n" \ " 1 file changed, 0 insertions(+), 0 deletions(-)\n" \ "\n" \ "diff --git a/binary.bin b/binary.bin\n" \ "index bd474b2519cc15eab801ff851cc7d50f0dee49a1..9ac35ff15cd8864aeafd889e4826a3150f0b06c4 100644\n" \ "GIT binary patch\n" \ "literal 5\n" \ "Mc${NkU}WL~000&M4gdfE\n" \ "\n" \ "literal 3\n" \ "Kc${Nk-~s>u4FC%O\n" \ "\n" \ "--\n" \ "libgit2 " LIBGIT2_VERSION "\n" \ "\n"; assert_email_match(expected, "8d7523f6fcb2404257889abe0d96f093d9f524f9", NULL); } void test_email_create__binary_not_included(void) { const char *expected = "From 8d7523f6fcb2404257889abe0d96f093d9f524f9 Mon Sep 17 00:00:00 2001\n" \ "From: Jacques Germishuys <[email protected]>\n" \ "Date: Sun, 13 Apr 2014 18:10:18 +0200\n" \ "Subject: [PATCH] Modified binary file\n" \ "\n" \ "---\n" \ " binary.bin | Bin 3 -> 5 bytes\n" \ " 1 file changed, 0 insertions(+), 0 deletions(-)\n" \ "\n" \ "diff --git a/binary.bin b/binary.bin\n" \ "index bd474b2..9ac35ff 100644\n" \ "Binary files a/binary.bin and b/binary.bin differ\n" \ "--\n" \ "libgit2 " LIBGIT2_VERSION "\n" \ "\n"; git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT; opts.diff_opts.flags &= ~GIT_DIFF_SHOW_BINARY; assert_email_match(expected, "8d7523f6fcb2404257889abe0d96f093d9f524f9", &opts); } void test_email_create__custom_summary_and_body(void) { const char *expected = "From 627e7e12d87e07a83fad5b6bfa25e86ead4a5270 Mon Sep 17 00:00:00 2001\n" \ "From: Patrick Steinhardt <[email protected]>\n" \ "Date: Tue, 24 Nov 2015 13:34:39 +0100\n" \ "Subject: [PPPPPATCH 2/4] This is a subject\n" \ "\n" \ "Modify content of file3.txt by appending a new line. Make this\n" \ "commit message somewhat longer to test behavior with newlines\n" \ "embedded in the message body.\n" \ "\n" \ "Also test if new paragraphs are included correctly.\n" \ "---\n" \ " file3.txt | 1 +\n" \ " 1 file changed, 1 insertion(+)\n" \ "\n" \ "diff --git a/file3.txt b/file3.txt\n" \ "index 9a2d780..7309653 100644\n" \ "--- a/file3.txt\n" \ "+++ b/file3.txt\n" \ "@@ -3,3 +3,4 @@ file3!\n" \ " file3\n" \ " file3\n" \ " file3\n" \ "+file3\n" \ "--\n" \ "libgit2 " LIBGIT2_VERSION "\n" \ "\n"; const char *summary = "This is a subject\nwith\nnewlines"; const char *body = "Modify content of file3.txt by appending a new line. Make this\n" \ "commit message somewhat longer to test behavior with newlines\n" \ "embedded in the message body.\n" \ "\n" \ "Also test if new paragraphs are included correctly."; git_oid oid; git_commit *commit = NULL; git_diff *diff = NULL; git_buf buf = GIT_BUF_INIT; git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT; opts.subject_prefix = "PPPPPATCH"; git_oid__fromstr(&oid, "627e7e12d87e07a83fad5b6bfa25e86ead4a5270", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_diff__commit(&diff, repo, commit, NULL)); cl_git_pass(git_email_create_from_diff(&buf, diff, 2, 4, &oid, summary, body, git_commit_author(commit), &opts)); cl_assert_equal_s(expected, buf.ptr); git_diff_free(diff); git_commit_free(commit); git_buf_dispose(&buf); } void test_email_create__commit_subjects(void) { git_email_create_options opts = GIT_EMAIL_CREATE_OPTIONS_INIT; assert_subject_match("[PATCH] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.reroll_number = 42; assert_subject_match("[PATCH v42] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.flags |= GIT_EMAIL_CREATE_ALWAYS_NUMBER; assert_subject_match("[PATCH v42 1/1] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.start_number = 9; assert_subject_match("[PATCH v42 9/9] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.subject_prefix = ""; assert_subject_match("[v42 9/9] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.reroll_number = 0; assert_subject_match("[9/9] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.start_number = 0; assert_subject_match("[1/1] Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); opts.flags = GIT_EMAIL_CREATE_OMIT_NUMBERS; assert_subject_match("Modify some content", "9264b96c6d104d0e07ae33d3007b6a48246c6f92", &opts); }
libgit2-main
tests/libgit2/email/create.c
#include "clar_libgit2.h" #include "../diff/diff_helpers.h" static git_repository *g_repo = NULL; void test_stress_diff__initialize(void) { } void test_stress_diff__cleanup(void) { cl_git_sandbox_cleanup(); } #define ANOTHER_POEM \ "OH, glorious are the guarded heights\nWhere guardian souls abide—\nSelf-exiled from our gross delights—\nAbove, beyond, outside:\nAn ampler arc their spirit swings—\nCommands a juster view—\nWe have their word for all these things,\nNo doubt their words are true.\n\nYet we, the bond slaves of our day,\nWhom dirt and danger press—\nCo-heirs of insolence, delay,\nAnd leagued unfaithfulness—\nSuch is our need must seek indeed\nAnd, having found, engage\nThe men who merely do the work\nFor which they draw the wage.\n\nFrom forge and farm and mine and bench,\nDeck, altar, outpost lone—\nMill, school, battalion, counter, trench,\nRail, senate, sheepfold, throne—\nCreation's cry goes up on high\nFrom age to cheated age:\n\"Send us the men who do the work\n\"For which they draw the wage!\"\n" static void test_with_many(int expected_new) { git_index *index; git_tree *tree, *new_tree; git_diff *diff = NULL; diff_expects exp; git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT; git_diff_find_options opts = GIT_DIFF_FIND_OPTIONS_INIT; cl_git_pass(git_repository_index(&index, g_repo)); cl_git_pass( git_revparse_single((git_object **)&tree, g_repo, "HEAD^{tree}")); cl_git_pass(p_rename("renames/ikeepsix.txt", "renames/ikeepsix2.txt")); cl_git_pass(git_index_remove_bypath(index, "ikeepsix.txt")); cl_git_pass(git_index_add_bypath(index, "ikeepsix2.txt")); cl_git_pass(git_index_write(index)); cl_git_pass(git_diff_tree_to_index(&diff, g_repo, tree, index, &diffopts)); memset(&exp, 0, sizeof(exp)); cl_git_pass(git_diff_foreach( diff, diff_file_cb, NULL, NULL, NULL, &exp)); cl_assert_equal_i(1, exp.file_status[GIT_DELTA_DELETED]); cl_assert_equal_i(expected_new + 1, exp.file_status[GIT_DELTA_ADDED]); cl_assert_equal_i(expected_new + 2, exp.files); opts.flags = GIT_DIFF_FIND_ALL; cl_git_pass(git_diff_find_similar(diff, &opts)); memset(&exp, 0, sizeof(exp)); cl_git_pass(git_diff_foreach( diff, diff_file_cb, NULL, NULL, NULL, &exp)); cl_assert_equal_i(1, exp.file_status[GIT_DELTA_RENAMED]); cl_assert_equal_i(expected_new, exp.file_status[GIT_DELTA_ADDED]); cl_assert_equal_i(expected_new + 1, exp.files); git_diff_free(diff); cl_repo_commit_from_index(NULL, g_repo, NULL, 1372350000, "yoyoyo"); cl_git_pass(git_revparse_single( (git_object **)&new_tree, g_repo, "HEAD^{tree}")); cl_git_pass(git_diff_tree_to_tree( &diff, g_repo, tree, new_tree, &diffopts)); memset(&exp, 0, sizeof(exp)); cl_git_pass(git_diff_foreach( diff, diff_file_cb, NULL, NULL, NULL, &exp)); cl_assert_equal_i(1, exp.file_status[GIT_DELTA_DELETED]); cl_assert_equal_i(expected_new + 1, exp.file_status[GIT_DELTA_ADDED]); cl_assert_equal_i(expected_new + 2, exp.files); opts.flags = GIT_DIFF_FIND_ALL; cl_git_pass(git_diff_find_similar(diff, &opts)); memset(&exp, 0, sizeof(exp)); cl_git_pass(git_diff_foreach( diff, diff_file_cb, NULL, NULL, NULL, &exp)); cl_assert_equal_i(1, exp.file_status[GIT_DELTA_RENAMED]); cl_assert_equal_i(expected_new, exp.file_status[GIT_DELTA_ADDED]); cl_assert_equal_i(expected_new + 1, exp.files); git_diff_free(diff); git_tree_free(new_tree); git_tree_free(tree); git_index_free(index); } void test_stress_diff__rename_big_files(void) { git_index *index; char tmp[64]; int i, j; git_str b = GIT_STR_INIT; g_repo = cl_git_sandbox_init("renames"); cl_git_pass(git_repository_index(&index, g_repo)); for (i = 0; i < 100; i += 1) { p_snprintf(tmp, sizeof(tmp), "renames/newfile%03d", i); for (j = i * 256; j > 0; --j) git_str_printf(&b, "more content %d\n", i); cl_git_mkfile(tmp, b.ptr); } for (i = 0; i < 100; i += 1) { p_snprintf(tmp, sizeof(tmp), "renames/newfile%03d", i); cl_git_pass(git_index_add_bypath(index, tmp + strlen("renames/"))); } git_str_dispose(&b); git_index_free(index); test_with_many(100); } void test_stress_diff__rename_many_files(void) { git_index *index; char tmp[64]; int i; git_str b = GIT_STR_INIT; g_repo = cl_git_sandbox_init("renames"); cl_git_pass(git_repository_index(&index, g_repo)); git_str_printf(&b, "%08d\n" ANOTHER_POEM "%08d\n" ANOTHER_POEM ANOTHER_POEM, 0, 0); for (i = 0; i < 2500; i += 1) { p_snprintf(tmp, sizeof(tmp), "renames/newfile%03d", i); p_snprintf(b.ptr, 9, "%08d", i); b.ptr[8] = '\n'; cl_git_mkfile(tmp, b.ptr); } git_str_dispose(&b); for (i = 0; i < 2500; i += 1) { p_snprintf(tmp, sizeof(tmp), "renames/newfile%03d", i); cl_git_pass(git_index_add_bypath(index, tmp + strlen("renames/"))); } git_index_free(index); test_with_many(2500); }
libgit2-main
tests/libgit2/stress/diff.c
#include "clar_libgit2.h" #include "repository.h" #include "git2/sys/repository.h" #include "mailmap_testdata.h" static git_repository *g_repo; static git_mailmap *g_mailmap; static git_config *g_config; static const char string_mailmap[] = "# Simple Comment line\n" "<[email protected]> <[email protected]>\n" "Some Dude <[email protected]> nick1 <[email protected]>\n" "Other Author <[email protected]> nick2 <[email protected]>\n" "Other Author <[email protected]> <[email protected]>\n" "Phil Hill <[email protected]> # Comment at end of line\n" "<[email protected]> Joseph <[email protected]>\n" "Santa Claus <[email protected]> <[email protected]>\n" "Untracked <[email protected]>"; static const mailmap_entry entries[] = { { NULL, "[email protected]", NULL, "[email protected]" }, { "Some Dude", "[email protected]", "nick1", "[email protected]" }, { "Other Author", "[email protected]", "nick2", "[email protected]" }, { "Other Author", "[email protected]", NULL, "[email protected]" }, { "Phil Hill", NULL, NULL, "[email protected]" }, { NULL, "[email protected]", "Joseph", "[email protected]" }, { "Santa Claus", "[email protected]", NULL, "[email protected]" }, /* This entry isn't in the bare repository */ { "Untracked", NULL, NULL, "[email protected]" } }; void test_mailmap_parsing__initialize(void) { g_repo = NULL; g_mailmap = NULL; g_config = NULL; } void test_mailmap_parsing__cleanup(void) { git_mailmap_free(g_mailmap); git_config_free(g_config); cl_git_sandbox_cleanup(); } static void check_mailmap_entries( const git_mailmap *mailmap, const mailmap_entry *entries, size_t entries_size) { const git_mailmap_entry *parsed; size_t idx; /* Check the correct # of entries were parsed */ cl_assert_equal_sz(entries_size, git_vector_length(&mailmap->entries)); /* Make sure looking up each entry succeeds */ for (idx = 0; idx < entries_size; ++idx) { parsed = git_mailmap_entry_lookup( mailmap, entries[idx].replace_name, entries[idx].replace_email); cl_assert(parsed); cl_assert_equal_s(parsed->real_name, entries[idx].real_name); cl_assert_equal_s(parsed->real_email, entries[idx].real_email); cl_assert_equal_s(parsed->replace_name, entries[idx].replace_name); cl_assert_equal_s(parsed->replace_email, entries[idx].replace_email); } } static void check_mailmap_resolve( const git_mailmap *mailmap, const mailmap_entry *resolved, size_t resolved_size) { const char *resolved_name = NULL; const char *resolved_email = NULL; size_t idx; /* Check that the resolver behaves correctly */ for (idx = 0; idx < resolved_size; ++idx) { cl_git_pass(git_mailmap_resolve( &resolved_name, &resolved_email, mailmap, resolved[idx].replace_name, resolved[idx].replace_email)); cl_assert_equal_s(resolved_name, resolved[idx].real_name); cl_assert_equal_s(resolved_email, resolved[idx].real_email); } } static const mailmap_entry resolved_untracked[] = { { "Untracked", "[email protected]", "xx", "[email protected]" } }; void test_mailmap_parsing__string(void) { cl_git_pass(git_mailmap_from_buffer( &g_mailmap, string_mailmap, strlen(string_mailmap))); /* We should have parsed all of the entries */ check_mailmap_entries(g_mailmap, entries, ARRAY_SIZE(entries)); /* Check that resolving the entries works */ check_mailmap_resolve(g_mailmap, resolved, ARRAY_SIZE(resolved)); check_mailmap_resolve( g_mailmap, resolved_untracked, ARRAY_SIZE(resolved_untracked)); } void test_mailmap_parsing__windows_string(void) { git_str unixbuf = GIT_STR_INIT; git_str winbuf = GIT_STR_INIT; /* Parse with windows-style line endings */ git_str_attach_notowned(&unixbuf, string_mailmap, strlen(string_mailmap)); cl_git_pass(git_str_lf_to_crlf(&winbuf, &unixbuf)); cl_git_pass(git_mailmap_from_buffer(&g_mailmap, winbuf.ptr, winbuf.size)); git_str_dispose(&winbuf); /* We should have parsed all of the entries */ check_mailmap_entries(g_mailmap, entries, ARRAY_SIZE(entries)); /* Check that resolving the entries works */ check_mailmap_resolve(g_mailmap, resolved, ARRAY_SIZE(resolved)); check_mailmap_resolve( g_mailmap, resolved_untracked, ARRAY_SIZE(resolved_untracked)); } void test_mailmap_parsing__fromrepo(void) { g_repo = cl_git_sandbox_init("mailmap"); cl_check(!git_repository_is_bare(g_repo)); cl_git_pass(git_mailmap_from_repository(&g_mailmap, g_repo)); /* We should have parsed all of the entries */ check_mailmap_entries(g_mailmap, entries, ARRAY_SIZE(entries)); /* Check that resolving the entries works */ check_mailmap_resolve(g_mailmap, resolved, ARRAY_SIZE(resolved)); check_mailmap_resolve( g_mailmap, resolved_untracked, ARRAY_SIZE(resolved_untracked)); } static const mailmap_entry resolved_bare[] = { { "xx", "[email protected]", "xx", "[email protected]" } }; void test_mailmap_parsing__frombare(void) { g_repo = cl_git_sandbox_init("mailmap/.gitted"); cl_git_pass(git_repository_set_bare(g_repo)); cl_check(git_repository_is_bare(g_repo)); cl_git_pass(git_mailmap_from_repository(&g_mailmap, g_repo)); /* We should have parsed all of the entries, except for the untracked one */ check_mailmap_entries(g_mailmap, entries, ARRAY_SIZE(entries) - 1); /* Check that resolving the entries works */ check_mailmap_resolve(g_mailmap, resolved, ARRAY_SIZE(resolved)); check_mailmap_resolve( g_mailmap, resolved_bare, ARRAY_SIZE(resolved_bare)); } static const mailmap_entry resolved_with_file_override[] = { { "Brad", "[email protected]", "Brad", "[email protected]" }, { "Brad L", "[email protected]", "Brad L", "[email protected]" }, { "Some Dude", "[email protected]", "nick1", "[email protected]" }, { "Other Author", "[email protected]", "nick2", "[email protected]" }, { "nick3", "[email protected]", "nick3", "[email protected]" }, { "Other Author", "[email protected]", "Some Garbage", "[email protected]" }, { "Joseph", "[email protected]", "Joseph", "[email protected]" }, { "Santa Claus", "[email protected]", "Clause", "[email protected]" }, { "Charles", "[email protected]", "Charles", "[email protected]" }, /* This name is overridden by file_override */ { "File Override", "[email protected]", "unknown", "[email protected]" }, { "Other Name", "[email protected]", "override", "[email protected]" } }; void test_mailmap_parsing__file_config(void) { g_repo = cl_git_sandbox_init("mailmap"); cl_git_pass(git_repository_config(&g_config, g_repo)); cl_git_pass(git_config_set_string( g_config, "mailmap.file", cl_fixture("mailmap/file_override"))); cl_git_pass(git_mailmap_from_repository(&g_mailmap, g_repo)); /* Check we don't have duplicate entries */ cl_assert_equal_sz(git_vector_length(&g_mailmap->entries), 9); /* Check that resolving the entries works */ check_mailmap_resolve( g_mailmap, resolved_with_file_override, ARRAY_SIZE(resolved_with_file_override)); } static const mailmap_entry resolved_with_blob_override[] = { { "Brad", "[email protected]", "Brad", "[email protected]" }, { "Brad L", "[email protected]", "Brad L", "[email protected]" }, { "Some Dude", "[email protected]", "nick1", "[email protected]" }, { "Other Author", "[email protected]", "nick2", "[email protected]" }, { "nick3", "[email protected]", "nick3", "[email protected]" }, { "Other Author", "[email protected]", "Some Garbage", "[email protected]" }, { "Joseph", "[email protected]", "Joseph", "[email protected]" }, { "Santa Claus", "[email protected]", "Clause", "[email protected]" }, { "Charles", "[email protected]", "Charles", "[email protected]" }, /* This name is overridden by blob_override */ { "Blob Override", "[email protected]", "unknown", "[email protected]" }, { "Other Name", "[email protected]", "override", "[email protected]" } }; void test_mailmap_parsing__blob_config(void) { g_repo = cl_git_sandbox_init("mailmap"); cl_git_pass(git_repository_config(&g_config, g_repo)); cl_git_pass(git_config_set_string( g_config, "mailmap.blob", "HEAD:blob_override")); cl_git_pass(git_mailmap_from_repository(&g_mailmap, g_repo)); /* Check we don't have duplicate entries */ cl_assert_equal_sz(git_vector_length(&g_mailmap->entries), 9); /* Check that resolving the entries works */ check_mailmap_resolve( g_mailmap, resolved_with_blob_override, ARRAY_SIZE(resolved_with_blob_override)); } static const mailmap_entry bare_resolved_with_blob_override[] = { /* As mailmap.blob is set, we won't load HEAD:.mailmap */ { "Brad", "[email protected]", "Brad", "[email protected]" }, { "Brad L", "[email protected]", "Brad L", "[email protected]" }, { "nick1", "[email protected]", "nick1", "[email protected]" }, { "nick2", "[email protected]", "nick2", "[email protected]" }, { "nick3", "[email protected]", "nick3", "[email protected]" }, { "Some Garbage", "[email protected]", "Some Garbage", "[email protected]" }, { "Joseph", "[email protected]", "Joseph", "[email protected]" }, { "Clause", "[email protected]", "Clause", "[email protected]" }, { "Charles", "[email protected]", "Charles", "[email protected]" }, /* This name is overridden by blob_override */ { "Blob Override", "[email protected]", "unknown", "[email protected]" }, { "Other Name", "[email protected]", "override", "[email protected]" } }; void test_mailmap_parsing__bare_blob_config(void) { g_repo = cl_git_sandbox_init("mailmap/.gitted"); cl_git_pass(git_repository_set_bare(g_repo)); cl_check(git_repository_is_bare(g_repo)); cl_git_pass(git_repository_config(&g_config, g_repo)); cl_git_pass(git_config_set_string( g_config, "mailmap.blob", "HEAD:blob_override")); cl_git_pass(git_mailmap_from_repository(&g_mailmap, g_repo)); /* Check that we only have the 2 entries */ cl_assert_equal_sz(git_vector_length(&g_mailmap->entries), 2); /* Check that resolving the entries works */ check_mailmap_resolve( g_mailmap, bare_resolved_with_blob_override, ARRAY_SIZE(bare_resolved_with_blob_override)); }
libgit2-main
tests/libgit2/mailmap/parsing.c
#include "clar.h" #include "clar_libgit2.h" #include "common.h" #include "mailmap.h" static git_mailmap *mailmap = NULL; const char TEST_MAILMAP[] = "Foo bar <[email protected]> <[email protected]> \n" "Blatantly invalid line\n" "Foo bar <[email protected]> <[email protected]>\n" "<[email protected]> <[email protected]>\n" "<[email protected]> Other Name <[email protected]>\n"; struct { const char *real_name; const char *real_email; const char *replace_name; const char *replace_email; } expected[] = { { "Foo bar", "[email protected]", NULL, "[email protected]" }, { "Foo bar", "[email protected]", NULL, "[email protected]" }, { NULL, "[email protected]", NULL, "[email protected]" }, { NULL, "[email protected]", "Other Name", "[email protected]" } }; void test_mailmap_basic__initialize(void) { cl_git_pass(git_mailmap_from_buffer( &mailmap, TEST_MAILMAP, strlen(TEST_MAILMAP))); } void test_mailmap_basic__cleanup(void) { git_mailmap_free(mailmap); mailmap = NULL; } void test_mailmap_basic__entry(void) { size_t idx; const git_mailmap_entry *entry; /* Check that we have the expected # of entries */ cl_assert_equal_sz(ARRAY_SIZE(expected), git_vector_length(&mailmap->entries)); for (idx = 0; idx < ARRAY_SIZE(expected); ++idx) { /* Try to look up each entry and make sure they match */ entry = git_mailmap_entry_lookup( mailmap, expected[idx].replace_name, expected[idx].replace_email); cl_assert(entry); cl_assert_equal_s(entry->real_name, expected[idx].real_name); cl_assert_equal_s(entry->real_email, expected[idx].real_email); cl_assert_equal_s(entry->replace_name, expected[idx].replace_name); cl_assert_equal_s(entry->replace_email, expected[idx].replace_email); } } void test_mailmap_basic__lookup_not_found(void) { const git_mailmap_entry *entry = git_mailmap_entry_lookup( mailmap, "Whoever", "[email protected]"); cl_assert(!entry); } void test_mailmap_basic__lookup(void) { const git_mailmap_entry *entry = git_mailmap_entry_lookup( mailmap, "Typoed the name once", "[email protected]"); cl_assert(entry); cl_assert_equal_s(entry->real_name, "Foo bar"); } void test_mailmap_basic__empty_email_query(void) { const char *name; const char *email; cl_git_pass(git_mailmap_resolve( &name, &email, mailmap, "Author name", "[email protected]")); cl_assert_equal_s(name, "Author name"); cl_assert_equal_s(email, "[email protected]"); } void test_mailmap_basic__name_matching(void) { const char *name; const char *email; cl_git_pass(git_mailmap_resolve( &name, &email, mailmap, "Other Name", "[email protected]")); cl_assert_equal_s(name, "Other Name"); cl_assert_equal_s(email, "[email protected]"); cl_git_pass(git_mailmap_resolve( &name, &email, mailmap, "Other Name That Doesn't Match", "[email protected]")); cl_assert_equal_s(name, "Other Name That Doesn't Match"); cl_assert_equal_s(email, "[email protected]"); }
libgit2-main
tests/libgit2/mailmap/basic.c
#include "clar_libgit2.h" #include "git2/repository.h" #include "git2/blame.h" #include "mailmap.h" #include "mailmap_testdata.h" static git_repository *g_repo; static git_blame *g_blame; void test_mailmap_blame__initialize(void) { g_repo = NULL; g_blame = NULL; } void test_mailmap_blame__cleanup(void) { git_blame_free(g_blame); cl_git_sandbox_cleanup(); } void test_mailmap_blame__hunks(void) { size_t idx = 0; const git_blame_hunk *hunk = NULL; git_blame_options opts = GIT_BLAME_OPTIONS_INIT; g_repo = cl_git_sandbox_init("mailmap"); opts.flags |= GIT_BLAME_USE_MAILMAP; cl_git_pass(git_blame_file(&g_blame, g_repo, "file.txt", &opts)); cl_assert(g_blame); for (idx = 0; idx < ARRAY_SIZE(resolved); ++idx) { hunk = git_blame_get_hunk_byline(g_blame, idx + 1); cl_assert(hunk->final_signature != NULL); cl_assert(hunk->orig_signature != NULL); cl_assert_equal_s(hunk->final_signature->name, resolved[idx].real_name); cl_assert_equal_s(hunk->final_signature->email, resolved[idx].real_email); } } void test_mailmap_blame__hunks_no_mailmap(void) { size_t idx = 0; const git_blame_hunk *hunk = NULL; git_blame_options opts = GIT_BLAME_OPTIONS_INIT; g_repo = cl_git_sandbox_init("mailmap"); cl_git_pass(git_blame_file(&g_blame, g_repo, "file.txt", &opts)); cl_assert(g_blame); for (idx = 0; idx < ARRAY_SIZE(resolved); ++idx) { hunk = git_blame_get_hunk_byline(g_blame, idx + 1); cl_assert(hunk->final_signature != NULL); cl_assert(hunk->orig_signature != NULL); cl_assert_equal_s(hunk->final_signature->name, resolved[idx].replace_name); cl_assert_equal_s(hunk->final_signature->email, resolved[idx].replace_email); } }
libgit2-main
tests/libgit2/mailmap/blame.c
#include "clar_libgit2.h" #include "remote.h" #include "repository.h" static git_repository *repo1; static git_repository *repo2; static char* repo1_path; static char* repo2_path; static const char *REPO1_REFNAME = "refs/heads/main"; static const char *REPO2_REFNAME = "refs/remotes/repo1/main"; static char *FORCE_FETCHSPEC = "+refs/heads/main:refs/remotes/repo1/main"; static char *NON_FORCE_FETCHSPEC = "refs/heads/main:refs/remotes/repo1/main"; void test_remote_fetch__initialize(void) { git_config *c; git_str repo1_path_buf = GIT_STR_INIT; git_str repo2_path_buf = GIT_STR_INIT; const char *sandbox = clar_sandbox_path(); cl_git_pass(git_str_joinpath(&repo1_path_buf, sandbox, "fetchtest_repo1")); repo1_path = git_str_detach(&repo1_path_buf); cl_git_pass(git_repository_init(&repo1, repo1_path, true)); cl_git_pass(git_str_joinpath(&repo2_path_buf, sandbox, "fetchtest_repo2")); repo2_path = git_str_detach(&repo2_path_buf); cl_git_pass(git_repository_init(&repo2, repo2_path, true)); cl_git_pass(git_repository_config(&c, repo1)); cl_git_pass(git_config_set_string(c, "user.email", "some@email")); cl_git_pass(git_config_set_string(c, "user.name", "some@name")); git_config_free(c); git_str_dispose(&repo1_path_buf); git_str_dispose(&repo2_path_buf); } void test_remote_fetch__cleanup(void) { git_repository_free(repo1); git_repository_free(repo2); cl_git_pass(git_futils_rmdir_r(repo1_path, NULL, GIT_RMDIR_REMOVE_FILES)); free(repo1_path); cl_git_pass(git_futils_rmdir_r(repo2_path, NULL, GIT_RMDIR_REMOVE_FILES)); free(repo2_path); } /** * This checks that the '+' flag on fetchspecs is respected. We create a * repository that has a reference to two commits, one a child of the other. * We fetch this repository into a second repository. Then we reset the * reference in the first repository and run the fetch again. If the '+' flag * is used then the reference in the second repository will change, but if it * is not then it should stay the same. * * @param commit1id A pointer to an OID which will be populated with the first * commit. * @param commit2id A pointer to an OID which will be populated with the second * commit, which is a descendant of the first. * @param force Whether to use a spec with '+' prefixed to force the refs * to update */ static void do_time_travelling_fetch(git_oid *commit1id, git_oid *commit2id, bool force) { char *refspec_strs = { force ? FORCE_FETCHSPEC : NON_FORCE_FETCHSPEC, }; git_strarray refspecs = { .count = 1, .strings = &refspec_strs, }; /* create two commits in repo 1 and a reference to them */ { git_oid empty_tree_id; git_tree *empty_tree; git_signature *sig; git_treebuilder *tb; cl_git_pass(git_treebuilder_new(&tb, repo1, NULL)); cl_git_pass(git_treebuilder_write(&empty_tree_id, tb)); cl_git_pass(git_tree_lookup(&empty_tree, repo1, &empty_tree_id)); cl_git_pass(git_signature_default(&sig, repo1)); cl_git_pass(git_commit_create(commit1id, repo1, REPO1_REFNAME, sig, sig, NULL, "one", empty_tree, 0, NULL)); cl_git_pass(git_commit_create_v(commit2id, repo1, REPO1_REFNAME, sig, sig, NULL, "two", empty_tree, 1, commit1id)); git_tree_free(empty_tree); git_signature_free(sig); git_treebuilder_free(tb); } /* fetch the reference via the remote */ { git_remote *remote; cl_git_pass(git_remote_create_anonymous(&remote, repo2, git_repository_path(repo1))); cl_git_pass(git_remote_fetch(remote, &refspecs, NULL, "some message")); git_remote_free(remote); } /* assert that repo2 references the second commit */ { const git_oid *target; git_reference *ref; cl_git_pass(git_reference_lookup(&ref, repo2, REPO2_REFNAME)); target = git_reference_target(ref); cl_assert_equal_b(git_oid_cmp(target, commit2id), 0); git_reference_free(ref); } /* set the reference in repo1 to point to the older commit */ { git_reference *ref; git_reference *ref2; cl_git_pass(git_reference_lookup(&ref, repo1, REPO1_REFNAME)); cl_git_pass(git_reference_set_target(&ref2, ref, commit1id, "rollback")); git_reference_free(ref); git_reference_free(ref2); } /* fetch the reference again */ { git_remote *remote; cl_git_pass(git_remote_create_anonymous(&remote, repo2, git_repository_path(repo1))); cl_git_pass(git_remote_fetch(remote, &refspecs, NULL, "some message")); git_remote_free(remote); } } void test_remote_fetch__dont_update_refs_if_not_descendant_and_not_force(void) { const git_oid *target; git_oid commit1id; git_oid commit2id; git_reference *ref; do_time_travelling_fetch(&commit1id, &commit2id, false); /* assert that the reference in repo2 has not changed */ cl_git_pass(git_reference_lookup(&ref, repo2, REPO2_REFNAME)); target = git_reference_target(ref); cl_assert_equal_b(git_oid_cmp(target, &commit2id), 0); git_reference_free(ref); } void test_remote_fetch__do_update_refs_if_not_descendant_and_force(void) { const git_oid *target; git_oid commit1id; git_oid commit2id; git_reference *ref; do_time_travelling_fetch(&commit1id, &commit2id, true); /* assert that the reference in repo2 has changed */ cl_git_pass(git_reference_lookup(&ref, repo2, REPO2_REFNAME)); target = git_reference_target(ref); cl_assert_equal_b(git_oid_cmp(target, &commit1id), 0); git_reference_free(ref); }
libgit2-main
tests/libgit2/remote/fetch.c
#include "clar_libgit2.h" #include "remote.h" #include "repository.h" #define REPO_PATH "testrepo2/.gitted" #define REMOTE_ORIGIN "origin" #define REMOTE_INSTEADOF_URL_FETCH "insteadof-url-fetch" #define REMOTE_INSTEADOF_URL_PUSH "insteadof-url-push" #define REMOTE_INSTEADOF_URL_BOTH "insteadof-url-both" #define REMOTE_INSTEADOF_PUSHURL_FETCH "insteadof-pushurl-fetch" #define REMOTE_INSTEADOF_PUSHURL_PUSH "insteadof-pushurl-push" #define REMOTE_INSTEADOF_PUSHURL_BOTH "insteadof-pushurl-both" static git_repository *g_repo; static git_remote *g_remote; void test_remote_insteadof__initialize(void) { g_repo = NULL; g_remote = NULL; } void test_remote_insteadof__cleanup(void) { git_repository_free(g_repo); git_remote_free(g_remote); } void test_remote_insteadof__not_applicable(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_ORIGIN)); cl_assert_equal_s( git_remote_url(g_remote), "https://github.com/libgit2/false.git"); cl_assert_equal_p(git_remote_pushurl(g_remote), NULL); } void test_remote_insteadof__url_insteadof_fetch(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_INSTEADOF_URL_FETCH)); cl_assert_equal_s( git_remote_url(g_remote), "http://github.com/url/fetch/libgit2"); cl_assert_equal_p(git_remote_pushurl(g_remote), NULL); } void test_remote_insteadof__url_insteadof_push(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_INSTEADOF_URL_PUSH)); cl_assert_equal_s( git_remote_url(g_remote), "http://example.com/url/push/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "[email protected]:url/push/libgit2"); } void test_remote_insteadof__url_insteadof_both(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_INSTEADOF_URL_BOTH)); cl_assert_equal_s( git_remote_url(g_remote), "http://github.com/url/both/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "[email protected]:url/both/libgit2"); } void test_remote_insteadof__pushurl_insteadof_fetch(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_INSTEADOF_PUSHURL_FETCH)); cl_assert_equal_s( git_remote_url(g_remote), "http://github.com/url/fetch/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "http://github.com/url/fetch/libgit2-push"); } void test_remote_insteadof__pushurl_insteadof_push(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_INSTEADOF_PUSHURL_PUSH)); cl_assert_equal_s( git_remote_url(g_remote), "http://example.com/url/push/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "http://example.com/url/push/libgit2-push"); } void test_remote_insteadof__pushurl_insteadof_both(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_lookup(&g_remote, g_repo, REMOTE_INSTEADOF_PUSHURL_BOTH)); cl_assert_equal_s( git_remote_url(g_remote), "http://github.com/url/both/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "http://github.com/url/both/libgit2-push"); } void test_remote_insteadof__anonymous_remote_fetch(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_create_anonymous(&g_remote, g_repo, "http://example.com/url/fetch/libgit2")); cl_assert_equal_s( git_remote_url(g_remote), "http://github.com/url/fetch/libgit2"); cl_assert_equal_p(git_remote_pushurl(g_remote), NULL); } void test_remote_insteadof__anonymous_remote_push(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_create_anonymous(&g_remote, g_repo, "http://example.com/url/push/libgit2")); cl_assert_equal_s( git_remote_url(g_remote), "http://example.com/url/push/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "[email protected]:url/push/libgit2"); } void test_remote_insteadof__anonymous_remote_both(void) { cl_git_pass(git_repository_open(&g_repo, cl_fixture(REPO_PATH))); cl_git_pass(git_remote_create_anonymous(&g_remote, g_repo, "http://example.com/url/both/libgit2")); cl_assert_equal_s( git_remote_url(g_remote), "http://github.com/url/both/libgit2"); cl_assert_equal_s( git_remote_pushurl(g_remote), "[email protected]:url/both/libgit2"); }
libgit2-main
tests/libgit2/remote/insteadof.c
#include "clar_libgit2.h" #include "config/config_helpers.h" static git_repository *_repo; #define TEST_URL "http://github.com/libgit2/libgit2.git" void test_remote_list__initialize(void) { _repo = cl_git_sandbox_init("testrepo"); } void test_remote_list__cleanup(void) { cl_git_sandbox_cleanup(); } void test_remote_list__always_checks_disk_config(void) { git_repository *repo; git_strarray remotes; git_remote *remote; cl_git_pass(git_repository_open(&repo, git_repository_path(_repo))); cl_git_pass(git_remote_list(&remotes, _repo)); cl_assert_equal_sz(remotes.count, 1); git_strarray_dispose(&remotes); cl_git_pass(git_remote_create(&remote, _repo, "valid-name", TEST_URL)); cl_git_pass(git_remote_list(&remotes, _repo)); cl_assert_equal_sz(remotes.count, 2); git_strarray_dispose(&remotes); cl_git_pass(git_remote_list(&remotes, repo)); cl_assert_equal_sz(remotes.count, 2); git_strarray_dispose(&remotes); git_repository_free(repo); git_remote_free(remote); }
libgit2-main
tests/libgit2/remote/list.c
#include "clar_libgit2.h" #include "futils.h" #include "net.h" #include "remote.h" static git_repository *repo; static git_net_url url = GIT_NET_URL_INIT; static int orig_proxies_need_reset = 0; static char *orig_http_proxy = NULL; static char *orig_https_proxy = NULL; static char *orig_no_proxy = NULL; void test_remote_httpproxy__initialize(void) { git_remote *remote; repo = cl_git_sandbox_init("testrepo"); cl_git_pass(git_remote_create(&remote, repo, "lg2", "https://github.com/libgit2/libgit2")); cl_git_pass(git_net_url_parse(&url, "https://github.com/libgit2/libgit2")); git_remote_free(remote); orig_proxies_need_reset = 0; } void test_remote_httpproxy__cleanup(void) { if (orig_proxies_need_reset) { cl_setenv("HTTP_PROXY", orig_http_proxy); cl_setenv("HTTPS_PROXY", orig_https_proxy); cl_setenv("NO_PROXY", orig_no_proxy); git__free(orig_http_proxy); git__free(orig_https_proxy); git__free(orig_no_proxy); } git_net_url_dispose(&url); cl_git_sandbox_cleanup(); } static void assert_proxy_is(const char *expected) { git_remote *remote; char *proxy; cl_git_pass(git_remote_lookup(&remote, repo, "lg2")); cl_git_pass(git_remote__http_proxy(&proxy, remote, &url)); if (expected) cl_assert_equal_s(proxy, expected); else cl_assert_equal_p(proxy, expected); git_remote_free(remote); git__free(proxy); } static void assert_config_match(const char *config, const char *expected) { git_remote *remote; char *proxy; if (config) cl_repo_set_string(repo, config, expected); cl_git_pass(git_remote_lookup(&remote, repo, "lg2")); cl_git_pass(git_remote__http_proxy(&proxy, remote, &url)); if (expected) cl_assert_equal_s(proxy, expected); else cl_assert_equal_p(proxy, expected); git_remote_free(remote); git__free(proxy); } void test_remote_httpproxy__config_overrides(void) { /* * http.proxy should be honored, then http.<url>.proxy should * be honored in increasing specificity of the url. finally, * remote.<name>.proxy is the most specific. */ assert_config_match(NULL, NULL); assert_config_match("http.proxy", "http://localhost:1/"); assert_config_match("http.https://github.com.proxy", "http://localhost:2/"); assert_config_match("http.https://github.com/.proxy", "http://localhost:3/"); assert_config_match("http.https://github.com/libgit2.proxy", "http://localhost:4/"); assert_config_match("http.https://github.com/libgit2/.proxy", "http://localhost:5/"); assert_config_match("http.https://github.com/libgit2/libgit2.proxy", "http://localhost:6/"); assert_config_match("remote.lg2.proxy", "http://localhost:7/"); } void test_remote_httpproxy__config_empty_overrides(void) { /* * with greater specificity, an empty config entry overrides * a set one */ assert_config_match("http.proxy", "http://localhost:1/"); assert_config_match("http.https://github.com.proxy", ""); assert_config_match("http.https://github.com/libgit2/libgit2.proxy", "http://localhost:2/"); assert_config_match("remote.lg2.proxy", ""); } static void assert_global_config_match(const char *config, const char *expected) { git_remote *remote; char *proxy; git_config* cfg; if (config) { cl_git_pass(git_config_open_default(&cfg)); git_config_set_string(cfg, config, expected); git_config_free(cfg); } cl_git_pass(git_remote_create_detached(&remote, "https://github.com/libgit2/libgit2")); cl_git_pass(git_remote__http_proxy(&proxy, remote, &url)); if (expected) cl_assert_equal_s(proxy, expected); else cl_assert_equal_p(proxy, expected); git_remote_free(remote); git__free(proxy); } void test_remote_httpproxy__config_overrides_detached_remote(void) { cl_fake_home(); assert_global_config_match(NULL, NULL); assert_global_config_match("http.proxy", "http://localhost:1/"); assert_global_config_match("http.https://github.com.proxy", "http://localhost:2/"); assert_global_config_match("http.https://github.com/.proxy", "http://localhost:3/"); assert_global_config_match("http.https://github.com/libgit2.proxy", "http://localhost:4/"); assert_global_config_match("http.https://github.com/libgit2/.proxy", "http://localhost:5/"); assert_global_config_match("http.https://github.com/libgit2/libgit2.proxy", "http://localhost:6/"); cl_git_pass(git_futils_rmdir_r("home", NULL, GIT_RMDIR_REMOVE_FILES)); } void test_remote_httpproxy__env(void) { orig_http_proxy = cl_getenv("HTTP_PROXY"); orig_https_proxy = cl_getenv("HTTPS_PROXY"); orig_no_proxy = cl_getenv("NO_PROXY"); orig_proxies_need_reset = 1; /* Clear everything for a fresh start */ cl_setenv("HTTP_PROXY", NULL); cl_setenv("HTTPS_PROXY", NULL); cl_setenv("NO_PROXY", NULL); /* HTTP proxy is ignored for HTTPS */ cl_setenv("HTTP_PROXY", "http://localhost:9/"); assert_proxy_is(NULL); /* HTTPS proxy is honored for HTTPS */ cl_setenv("HTTPS_PROXY", "http://localhost:10/"); assert_proxy_is("http://localhost:10/"); /* NO_PROXY is honored */ cl_setenv("NO_PROXY", "github.com:443"); assert_proxy_is(NULL); cl_setenv("NO_PROXY", "github.com:80"); assert_proxy_is("http://localhost:10/"); cl_setenv("NO_PROXY", "github.com"); assert_proxy_is(NULL); cl_setenv("NO_PROXY", "github.dev,github.com,github.foo"); assert_proxy_is(NULL); cl_setenv("HTTPS_PROXY", ""); assert_proxy_is(NULL); /* configuration overrides environment variables */ cl_setenv("HTTPS_PROXY", "http://localhost:10/"); cl_setenv("NO_PROXY", "github.none"); assert_config_match("http.https://github.com.proxy", "http://localhost:11/"); }
libgit2-main
tests/libgit2/remote/httpproxy.c
#include "clar_libgit2.h" #include "config/config_helpers.h" static git_repository *_repo; static git_config *_config; #define TEST_URL "http://github.com/libgit2/libgit2.git" void test_remote_create__initialize(void) { cl_fixture_sandbox("testrepo.git"); cl_git_pass(git_repository_open(&_repo, "testrepo.git")); cl_git_pass(git_repository_config(&_config, _repo)); } void test_remote_create__cleanup(void) { git_config_free(_config); git_repository_free(_repo); cl_fixture_cleanup("testrepo.git"); } void test_remote_create__manual(void) { git_remote *remote; cl_git_pass(git_config_set_string(_config, "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")); cl_git_pass(git_config_set_string(_config, "remote.origin.url", TEST_URL)); cl_git_pass(git_remote_lookup(&remote, _repo, "origin")); cl_assert_equal_s(git_remote_name(remote), "origin"); cl_assert_equal_s(git_remote_url(remote), TEST_URL); git_remote_free(remote); } void test_remote_create__named(void) { git_remote *remote; git_config *cfg; const char *cfg_val; size_t section_count = count_config_entries_match(_repo, "remote\\."); cl_git_pass(git_remote_create(&remote, _repo, "valid-name", TEST_URL)); cl_assert_equal_s(git_remote_name(remote), "valid-name"); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_repository_config_snapshot(&cfg, _repo)); cl_git_pass(git_config_get_string(&cfg_val, cfg, "remote.valid-name.fetch")); cl_assert_equal_s(cfg_val, "+refs/heads/*:refs/remotes/valid-name/*"); cl_git_pass(git_config_get_string(&cfg_val, cfg, "remote.valid-name.url")); cl_assert_equal_s(cfg_val, TEST_URL); cl_assert_equal_i(section_count + 2, count_config_entries_match(_repo, "remote\\.")); git_config_free(cfg); git_remote_free(remote); } void test_remote_create__named_fail_on_invalid_name(void) { const char *names[] = { NULL, "Inv@{id", "", "/", "//", ".lock", "a.lock", }; size_t i; for (i = 0; i < ARRAY_SIZE(names); i++) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, git_remote_create(&remote, _repo, names[i], TEST_URL)); cl_assert_equal_p(remote, NULL); } } void test_remote_create__named_fail_on_invalid_url(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_ERROR, git_remote_create(&remote, _repo, "bad-url", "")); cl_assert_equal_p(remote, NULL); } void test_remote_create__named_fail_on_conflicting_name(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EEXISTS, git_remote_create(&remote, _repo, "test", TEST_URL)); cl_assert_equal_p(remote, NULL); } void test_remote_create__with_fetchspec(void) { git_remote *remote; git_strarray array; size_t section_count = count_config_entries_match(_repo, "remote\\."); cl_git_pass(git_remote_create_with_fetchspec(&remote, _repo, "test-new", "git://github.com/libgit2/libgit2", "+refs/*:refs/*")); cl_assert_equal_s(git_remote_name(remote), "test-new"); cl_assert_equal_s(git_remote_url(remote), "git://github.com/libgit2/libgit2"); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_s("+refs/*:refs/*", array.strings[0]); cl_assert_equal_i(1, array.count); cl_assert_equal_i(section_count + 2, count_config_entries_match(_repo, "remote\\.")); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_empty_fetchspec(void) { git_remote *remote; git_strarray array; size_t section_count = count_config_entries_match(_repo, "remote\\."); cl_git_pass(git_remote_create_with_fetchspec(&remote, _repo, "test-new", "git://github.com/libgit2/libgit2", NULL)); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); cl_assert_equal_i(section_count + 1, count_config_entries_match(_repo, "remote\\.")); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_fetchspec_invalid_name(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, git_remote_create_with_fetchspec(&remote, _repo, NULL, TEST_URL, NULL)); cl_assert_equal_p(remote, NULL); } void test_remote_create__with_fetchspec_invalid_url(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, git_remote_create_with_fetchspec(&remote, _repo, NULL, "", NULL)); cl_assert_equal_p(remote, NULL); } void test_remote_create__anonymous(void) { git_remote *remote; git_strarray array; size_t section_count = count_config_entries_match(_repo, "remote\\."); cl_git_pass(git_remote_create_anonymous(&remote, _repo, TEST_URL)); cl_assert_equal_s(git_remote_name(remote), NULL); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); cl_assert_equal_i(section_count, count_config_entries_match(_repo, "remote\\.")); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__anonymous_invalid_url(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, git_remote_create_anonymous(&remote, _repo, "")); cl_assert_equal_p(remote, NULL); } void test_remote_create__detached(void) { git_remote *remote; git_strarray array; size_t section_count = count_config_entries_match(_repo, "remote\\."); cl_git_pass(git_remote_create_detached(&remote, TEST_URL)); cl_assert_equal_s(git_remote_name(remote), NULL); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), NULL); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); cl_assert_equal_i(section_count, count_config_entries_match(_repo, "remote\\.")); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__detached_invalid_url(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, git_remote_create_detached(&remote, "")); cl_assert_equal_p(remote, NULL); } void test_remote_create__with_opts_named(void) { git_remote *remote; git_strarray array; git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; opts.name = "test-new"; opts.repository = _repo; cl_git_pass(git_remote_create_with_opts(&remote, TEST_URL, &opts)); cl_assert_equal_s(git_remote_name(remote), "test-new"); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(1, array.count); cl_assert_equal_s("+refs/heads/*:refs/remotes/test-new/*", array.strings[0]); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_opts_named_and_fetchspec(void) { git_remote *remote; git_strarray array; git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; opts.name = "test-new"; opts.repository = _repo; opts.fetchspec = "+refs/*:refs/*"; cl_git_pass(git_remote_create_with_opts(&remote, TEST_URL, &opts)); cl_assert_equal_s(git_remote_name(remote), "test-new"); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(1, array.count); cl_assert_equal_s("+refs/*:refs/*", array.strings[0]); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_opts_named_no_fetchspec(void) { git_remote *remote; git_strarray array; git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; opts.name = "test-new"; opts.repository = _repo; opts.flags = GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC; cl_git_pass(git_remote_create_with_opts(&remote, TEST_URL, &opts)); cl_assert_equal_s(git_remote_name(remote), "test-new"); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_opts_anonymous(void) { git_remote *remote; git_strarray array; git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; opts.repository = _repo; cl_git_pass(git_remote_create_with_opts(&remote, TEST_URL, &opts)); cl_assert_equal_s(git_remote_name(remote), NULL); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), _repo); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_opts_detached(void) { git_remote *remote; git_strarray array; git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; cl_git_pass(git_remote_create_with_opts(&remote, TEST_URL, &opts)); cl_assert_equal_s(git_remote_name(remote), NULL); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), NULL); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); git_strarray_dispose(&array); git_remote_free(remote); cl_git_pass(git_remote_create_with_opts(&remote, TEST_URL, NULL)); cl_assert_equal_s(git_remote_name(remote), NULL); cl_assert_equal_s(git_remote_url(remote), TEST_URL); cl_assert_equal_p(git_remote_owner(remote), NULL); cl_git_pass(git_remote_get_fetch_refspecs(&array, remote)); cl_assert_equal_i(0, array.count); git_strarray_dispose(&array); git_remote_free(remote); } void test_remote_create__with_opts_insteadof_disabled(void) { git_remote *remote; git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; opts.repository = _repo; opts.flags = GIT_REMOTE_CREATE_SKIP_INSTEADOF; cl_git_pass(git_remote_create_with_opts(&remote, "http://example.com/libgit2/libgit2", &opts)); cl_assert_equal_s(git_remote_url(remote), "http://example.com/libgit2/libgit2"); cl_assert_equal_p(git_remote_pushurl(remote), NULL); git_remote_free(remote); } static int create_with_name(git_remote **remote, git_repository *repo, const char *name, const char *url) { git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT; opts.repository = repo; opts.name = name; return git_remote_create_with_opts(remote, url, &opts); } void test_remote_create__with_opts_invalid_name(void) { const char *names[] = { "Inv@{id", "", "/", "//", ".lock", "a.lock", }; size_t i; for (i = 0; i < ARRAY_SIZE(names); i++) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, create_with_name(&remote, _repo, names[i], TEST_URL)); cl_assert_equal_p(remote, NULL); } } void test_remote_create__with_opts_conflicting_name(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EEXISTS, create_with_name(&remote, _repo, "test", TEST_URL)); cl_assert_equal_p(remote, NULL); } void test_remote_create__with_opts_invalid_url(void) { git_remote *remote = NULL; cl_git_fail_with(GIT_EINVALIDSPEC, create_with_name(&remote, _repo, "test-new", "")); cl_assert_equal_p(remote, NULL); }
libgit2-main
tests/libgit2/remote/create.c
/* * Dummy project to validate header files * * This project is not intended to be executed, it should only include all * header files to make sure that they can be used with stricter compiler * settings than the libgit2 source files generally supports. */ #include "git2.h" int main(void) { return 0; }
libgit2-main
tests/headertest/headertest.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ void *realloc(void *ptr, size_t size); void *memmove(void *dest, const void *src, size_t n); size_t strlen(const char *s); typedef struct va_list_str *va_list; typedef struct git_vector { void **contents; size_t length; } git_vector; typedef struct git_buf { char *ptr; size_t asize, size; } git_buf; int git_vector_insert(git_vector *v, void *element) { if (!v) __coverity_panic__(); v->contents = realloc(v->contents, ++v->length); if (!v->contents) __coverity_panic__(); v->contents[v->length] = element; return 0; } int git_buf_len(const struct git_buf *buf) { return strlen(buf->ptr); } int git_buf_vprintf(git_buf *buf, const char *format, va_list ap) { char ch, *s; size_t len; __coverity_string_null_sink__(format); __coverity_string_size_sink__(format); ch = *format; ch = *(char *)ap; buf->ptr = __coverity_alloc__(len); __coverity_writeall__(buf->ptr); buf->size = len; return 0; } int git_buf_put(git_buf *buf, const char *data, size_t len) { buf->ptr = __coverity_alloc__(buf->size + len + 1); memmove(buf->ptr + buf->size, data, len); buf->size += len; buf->ptr[buf->size + len] = 0; return 0; } int git_buf_set(git_buf *buf, const void *data, size_t len) { buf->ptr = __coverity_alloc__(len + 1); memmove(buf->ptr, data, len); buf->size = len + 1; return 0; } void clar__fail( const char *file, int line, const char *error, const char *description, int should_abort) { if (should_abort) __coverity_panic__(); } void clar__assert( int condition, const char *file, int line, const char *error, const char *description, int should_abort) { if (!condition && should_abort) __coverity_panic__(); }
libgit2-main
script/user_model.c
/* * libgit2 "log" example - shows how to walk history and get commit info * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 rev walker APIs to roughly * simulate the output of `git log` and a few of command line arguments. * `git log` has many many options and this only shows a few of them. * * This does not have: * * - Robust error handling * - Colorized or paginated output formatting * - Most of the `git log` options * * This does have: * * - Examples of translating command line arguments to equivalent libgit2 * revwalker configuration calls * - Simplified options to apply pathspec limits and to show basic diffs */ /** log_state represents walker being configured while handling options */ struct log_state { git_repository *repo; const char *repodir; git_revwalk *walker; int hide; int sorting; int revisions; }; /** utility functions that are called to configure the walker */ static void set_sorting(struct log_state *s, unsigned int sort_mode); static void push_rev(struct log_state *s, git_object *obj, int hide); static int add_revision(struct log_state *s, const char *revstr); /** log_options holds other command line options that affect log output */ struct log_options { int show_diff; int show_log_size; int skip, limit; int min_parents, max_parents; git_time_t before; git_time_t after; const char *author; const char *committer; const char *grep; }; /** utility functions that parse options and help with log output */ static int parse_options( struct log_state *s, struct log_options *opt, int argc, char **argv); static void print_time(const git_time *intime, const char *prefix); static void print_commit(git_commit *commit, struct log_options *opts); static int match_with_parent(git_commit *commit, int i, git_diff_options *); /** utility functions for filtering */ static int signature_matches(const git_signature *sig, const char *filter); static int log_message_matches(const git_commit *commit, const char *filter); int lg2_log(git_repository *repo, int argc, char *argv[]) { int i, count = 0, printed = 0, parents, last_arg; struct log_state s; struct log_options opt; git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT; git_oid oid; git_commit *commit = NULL; git_pathspec *ps = NULL; /** Parse arguments and set up revwalker. */ last_arg = parse_options(&s, &opt, argc, argv); s.repo = repo; diffopts.pathspec.strings = &argv[last_arg]; diffopts.pathspec.count = argc - last_arg; if (diffopts.pathspec.count > 0) check_lg2(git_pathspec_new(&ps, &diffopts.pathspec), "Building pathspec", NULL); if (!s.revisions) add_revision(&s, NULL); /** Use the revwalker to traverse the history. */ printed = count = 0; for (; !git_revwalk_next(&oid, s.walker); git_commit_free(commit)) { check_lg2(git_commit_lookup(&commit, s.repo, &oid), "Failed to look up commit", NULL); parents = (int)git_commit_parentcount(commit); if (parents < opt.min_parents) continue; if (opt.max_parents > 0 && parents > opt.max_parents) continue; if (diffopts.pathspec.count > 0) { int unmatched = parents; if (parents == 0) { git_tree *tree; check_lg2(git_commit_tree(&tree, commit), "Get tree", NULL); if (git_pathspec_match_tree( NULL, tree, GIT_PATHSPEC_NO_MATCH_ERROR, ps) != 0) unmatched = 1; git_tree_free(tree); } else if (parents == 1) { unmatched = match_with_parent(commit, 0, &diffopts) ? 0 : 1; } else { for (i = 0; i < parents; ++i) { if (match_with_parent(commit, i, &diffopts)) unmatched--; } } if (unmatched > 0) continue; } if (!signature_matches(git_commit_author(commit), opt.author)) continue; if (!signature_matches(git_commit_committer(commit), opt.committer)) continue; if (!log_message_matches(commit, opt.grep)) continue; if (count++ < opt.skip) continue; if (opt.limit != -1 && printed++ >= opt.limit) { git_commit_free(commit); break; } print_commit(commit, &opt); if (opt.show_diff) { git_tree *a = NULL, *b = NULL; git_diff *diff = NULL; if (parents > 1) continue; check_lg2(git_commit_tree(&b, commit), "Get tree", NULL); if (parents == 1) { git_commit *parent; check_lg2(git_commit_parent(&parent, commit, 0), "Get parent", NULL); check_lg2(git_commit_tree(&a, parent), "Tree for parent", NULL); git_commit_free(parent); } check_lg2(git_diff_tree_to_tree( &diff, git_commit_owner(commit), a, b, &diffopts), "Diff commit with parent", NULL); check_lg2( git_diff_print(diff, GIT_DIFF_FORMAT_PATCH, diff_output, NULL), "Displaying diff", NULL); git_diff_free(diff); git_tree_free(a); git_tree_free(b); } } git_pathspec_free(ps); git_revwalk_free(s.walker); return 0; } /** Determine if the given git_signature does not contain the filter text. */ static int signature_matches(const git_signature *sig, const char *filter) { if (filter == NULL) return 1; if (sig != NULL && (strstr(sig->name, filter) != NULL || strstr(sig->email, filter) != NULL)) return 1; return 0; } static int log_message_matches(const git_commit *commit, const char *filter) { const char *message = NULL; if (filter == NULL) return 1; if ((message = git_commit_message(commit)) != NULL && strstr(message, filter) != NULL) return 1; return 0; } /** Push object (for hide or show) onto revwalker. */ static void push_rev(struct log_state *s, git_object *obj, int hide) { hide = s->hide ^ hide; /** Create revwalker on demand if it doesn't already exist. */ if (!s->walker) { check_lg2(git_revwalk_new(&s->walker, s->repo), "Could not create revision walker", NULL); git_revwalk_sorting(s->walker, s->sorting); } if (!obj) check_lg2(git_revwalk_push_head(s->walker), "Could not find repository HEAD", NULL); else if (hide) check_lg2(git_revwalk_hide(s->walker, git_object_id(obj)), "Reference does not refer to a commit", NULL); else check_lg2(git_revwalk_push(s->walker, git_object_id(obj)), "Reference does not refer to a commit", NULL); git_object_free(obj); } /** Parse revision string and add revs to walker. */ static int add_revision(struct log_state *s, const char *revstr) { git_revspec revs; int hide = 0; if (!revstr) { push_rev(s, NULL, hide); return 0; } if (*revstr == '^') { revs.flags = GIT_REVSPEC_SINGLE; hide = !hide; if (git_revparse_single(&revs.from, s->repo, revstr + 1) < 0) return -1; } else if (git_revparse(&revs, s->repo, revstr) < 0) return -1; if ((revs.flags & GIT_REVSPEC_SINGLE) != 0) push_rev(s, revs.from, hide); else { push_rev(s, revs.to, hide); if ((revs.flags & GIT_REVSPEC_MERGE_BASE) != 0) { git_oid base; check_lg2(git_merge_base(&base, s->repo, git_object_id(revs.from), git_object_id(revs.to)), "Could not find merge base", revstr); check_lg2( git_object_lookup(&revs.to, s->repo, &base, GIT_OBJECT_COMMIT), "Could not find merge base commit", NULL); push_rev(s, revs.to, hide); } push_rev(s, revs.from, !hide); } return 0; } /** Update revwalker with sorting mode. */ static void set_sorting(struct log_state *s, unsigned int sort_mode) { /** Open repo on demand if it isn't already open. */ if (!s->repo) { if (!s->repodir) s->repodir = "."; check_lg2(git_repository_open_ext(&s->repo, s->repodir, 0, NULL), "Could not open repository", s->repodir); } /** Create revwalker on demand if it doesn't already exist. */ if (!s->walker) check_lg2(git_revwalk_new(&s->walker, s->repo), "Could not create revision walker", NULL); if (sort_mode == GIT_SORT_REVERSE) s->sorting = s->sorting ^ GIT_SORT_REVERSE; else s->sorting = sort_mode | (s->sorting & GIT_SORT_REVERSE); git_revwalk_sorting(s->walker, s->sorting); } /** Helper to format a git_time value like Git. */ static void print_time(const git_time *intime, const char *prefix) { char sign, out[32]; struct tm *intm; int offset, hours, minutes; time_t t; offset = intime->offset; if (offset < 0) { sign = '-'; offset = -offset; } else { sign = '+'; } hours = offset / 60; minutes = offset % 60; t = (time_t)intime->time + (intime->offset * 60); intm = gmtime(&t); strftime(out, sizeof(out), "%a %b %e %T %Y", intm); printf("%s%s %c%02d%02d\n", prefix, out, sign, hours, minutes); } /** Helper to print a commit object. */ static void print_commit(git_commit *commit, struct log_options *opts) { char buf[GIT_OID_SHA1_HEXSIZE + 1]; int i, count; const git_signature *sig; const char *scan, *eol; git_oid_tostr(buf, sizeof(buf), git_commit_id(commit)); printf("commit %s\n", buf); if (opts->show_log_size) { printf("log size %d\n", (int)strlen(git_commit_message(commit))); } if ((count = (int)git_commit_parentcount(commit)) > 1) { printf("Merge:"); for (i = 0; i < count; ++i) { git_oid_tostr(buf, 8, git_commit_parent_id(commit, i)); printf(" %s", buf); } printf("\n"); } if ((sig = git_commit_author(commit)) != NULL) { printf("Author: %s <%s>\n", sig->name, sig->email); print_time(&sig->when, "Date: "); } printf("\n"); for (scan = git_commit_message(commit); scan && *scan; ) { for (eol = scan; *eol && *eol != '\n'; ++eol) /* find eol */; printf(" %.*s\n", (int)(eol - scan), scan); scan = *eol ? eol + 1 : NULL; } printf("\n"); } /** Helper to find how many files in a commit changed from its nth parent. */ static int match_with_parent(git_commit *commit, int i, git_diff_options *opts) { git_commit *parent; git_tree *a, *b; git_diff *diff; int ndeltas; check_lg2( git_commit_parent(&parent, commit, (size_t)i), "Get parent", NULL); check_lg2(git_commit_tree(&a, parent), "Tree for parent", NULL); check_lg2(git_commit_tree(&b, commit), "Tree for commit", NULL); check_lg2( git_diff_tree_to_tree(&diff, git_commit_owner(commit), a, b, opts), "Checking diff between parent and commit", NULL); ndeltas = (int)git_diff_num_deltas(diff); git_diff_free(diff); git_tree_free(a); git_tree_free(b); git_commit_free(parent); return ndeltas > 0; } /** Print a usage message for the program. */ static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: log [<options>]\n"); exit(1); } /** Parse some log command line options. */ static int parse_options( struct log_state *s, struct log_options *opt, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; memset(s, 0, sizeof(*s)); s->sorting = GIT_SORT_TIME; memset(opt, 0, sizeof(*opt)); opt->max_parents = -1; opt->limit = -1; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *a = argv[args.pos]; if (a[0] != '-') { if (!add_revision(s, a)) s->revisions++; else /** Try failed revision parse as filename. */ break; } else if (!match_arg_separator(&args)) { break; } else if (!strcmp(a, "--date-order")) set_sorting(s, GIT_SORT_TIME); else if (!strcmp(a, "--topo-order")) set_sorting(s, GIT_SORT_TOPOLOGICAL); else if (!strcmp(a, "--reverse")) set_sorting(s, GIT_SORT_REVERSE); else if (match_str_arg(&opt->author, &args, "--author")) /** Found valid --author */ ; else if (match_str_arg(&opt->committer, &args, "--committer")) /** Found valid --committer */ ; else if (match_str_arg(&opt->grep, &args, "--grep")) /** Found valid --grep */ ; else if (match_str_arg(&s->repodir, &args, "--git-dir")) /** Found git-dir. */ ; else if (match_int_arg(&opt->skip, &args, "--skip", 0)) /** Found valid --skip. */ ; else if (match_int_arg(&opt->limit, &args, "--max-count", 0)) /** Found valid --max-count. */ ; else if (a[1] >= '0' && a[1] <= '9') is_integer(&opt->limit, a + 1, 0); else if (match_int_arg(&opt->limit, &args, "-n", 0)) /** Found valid -n. */ ; else if (!strcmp(a, "--merges")) opt->min_parents = 2; else if (!strcmp(a, "--no-merges")) opt->max_parents = 1; else if (!strcmp(a, "--no-min-parents")) opt->min_parents = 0; else if (!strcmp(a, "--no-max-parents")) opt->max_parents = -1; else if (match_int_arg(&opt->max_parents, &args, "--max-parents=", 1)) /** Found valid --max-parents. */ ; else if (match_int_arg(&opt->min_parents, &args, "--min-parents=", 0)) /** Found valid --min_parents. */ ; else if (!strcmp(a, "-p") || !strcmp(a, "-u") || !strcmp(a, "--patch")) opt->show_diff = 1; else if (!strcmp(a, "--log-size")) opt->show_log_size = 1; else usage("Unsupported argument", a); } return args.pos; }
libgit2-main
examples/log.c
/* * libgit2 "diff" example - shows how to use the diff API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the use of the libgit2 diff APIs to * create `git_diff` objects and display them, emulating a number of * core Git `diff` command line options. * * This covers on a portion of the core Git diff options and doesn't * have particularly good error handling, but it should show most of * the core libgit2 diff APIs, including various types of diffs and * how to do renaming detection and patch formatting. */ static const char *colors[] = { "\033[m", /* reset */ "\033[1m", /* bold */ "\033[31m", /* red */ "\033[32m", /* green */ "\033[36m" /* cyan */ }; enum { OUTPUT_DIFF = (1 << 0), OUTPUT_STAT = (1 << 1), OUTPUT_SHORTSTAT = (1 << 2), OUTPUT_NUMSTAT = (1 << 3), OUTPUT_SUMMARY = (1 << 4) }; enum { CACHE_NORMAL = 0, CACHE_ONLY = 1, CACHE_NONE = 2 }; /** The 'diff_options' struct captures all the various parsed command line options. */ struct diff_options { git_diff_options diffopts; git_diff_find_options findopts; int color; int no_index; int cache; int output; git_diff_format_t format; const char *treeish1; const char *treeish2; const char *dir; }; /** These functions are implemented at the end */ static void usage(const char *message, const char *arg); static void parse_opts(struct diff_options *o, int argc, char *argv[]); static int color_printer( const git_diff_delta*, const git_diff_hunk*, const git_diff_line*, void*); static void diff_print_stats(git_diff *diff, struct diff_options *o); static void compute_diff_no_index(git_diff **diff, struct diff_options *o); int lg2_diff(git_repository *repo, int argc, char *argv[]) { git_tree *t1 = NULL, *t2 = NULL; git_diff *diff; struct diff_options o = { GIT_DIFF_OPTIONS_INIT, GIT_DIFF_FIND_OPTIONS_INIT, -1, -1, 0, 0, GIT_DIFF_FORMAT_PATCH, NULL, NULL, "." }; parse_opts(&o, argc, argv); /** * Possible argument patterns: * * * &lt;sha1&gt; &lt;sha2&gt; * * &lt;sha1&gt; --cached * * &lt;sha1&gt; * * --cached * * --nocache (don't use index data in diff at all) * * --no-index &lt;file1&gt; &lt;file2&gt; * * nothing * * Currently ranged arguments like &lt;sha1&gt;..&lt;sha2&gt; and &lt;sha1&gt;...&lt;sha2&gt; * are not supported in this example */ if (o.no_index >= 0) { compute_diff_no_index(&diff, &o); } else { if (o.treeish1) treeish_to_tree(&t1, repo, o.treeish1); if (o.treeish2) treeish_to_tree(&t2, repo, o.treeish2); if (t1 && t2) check_lg2( git_diff_tree_to_tree(&diff, repo, t1, t2, &o.diffopts), "diff trees", NULL); else if (o.cache != CACHE_NORMAL) { if (!t1) treeish_to_tree(&t1, repo, "HEAD"); if (o.cache == CACHE_NONE) check_lg2( git_diff_tree_to_workdir(&diff, repo, t1, &o.diffopts), "diff tree to working directory", NULL); else check_lg2( git_diff_tree_to_index(&diff, repo, t1, NULL, &o.diffopts), "diff tree to index", NULL); } else if (t1) check_lg2( git_diff_tree_to_workdir_with_index(&diff, repo, t1, &o.diffopts), "diff tree to working directory", NULL); else check_lg2( git_diff_index_to_workdir(&diff, repo, NULL, &o.diffopts), "diff index to working directory", NULL); /** Apply rename and copy detection if requested. */ if ((o.findopts.flags & GIT_DIFF_FIND_ALL) != 0) check_lg2( git_diff_find_similar(diff, &o.findopts), "finding renames and copies", NULL); } /** Generate simple output using libgit2 display helper. */ if (!o.output) o.output = OUTPUT_DIFF; if (o.output != OUTPUT_DIFF) diff_print_stats(diff, &o); if ((o.output & OUTPUT_DIFF) != 0) { if (o.color >= 0) fputs(colors[0], stdout); check_lg2( git_diff_print(diff, o.format, color_printer, &o.color), "displaying diff", NULL); if (o.color >= 0) fputs(colors[0], stdout); } /** Cleanup before exiting. */ git_diff_free(diff); git_tree_free(t1); git_tree_free(t2); return 0; } static void compute_diff_no_index(git_diff **diff, struct diff_options *o) { git_patch *patch = NULL; char *file1_str = NULL; char *file2_str = NULL; git_buf buf = {0}; if (!o->treeish1 || !o->treeish2) { usage("two files should be provided as arguments", NULL); } file1_str = read_file(o->treeish1); if (file1_str == NULL) { usage("file cannot be read", o->treeish1); } file2_str = read_file(o->treeish2); if (file2_str == NULL) { usage("file cannot be read", o->treeish2); } check_lg2( git_patch_from_buffers(&patch, file1_str, strlen(file1_str), o->treeish1, file2_str, strlen(file2_str), o->treeish2, &o->diffopts), "patch buffers", NULL); check_lg2( git_patch_to_buf(&buf, patch), "patch to buf", NULL); check_lg2( git_diff_from_buffer(diff, buf.ptr, buf.size), "diff from patch", NULL); git_patch_free(patch); git_buf_dispose(&buf); free(file1_str); free(file2_str); } static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: diff [<tree-oid> [<tree-oid>]]\n"); exit(1); } /** This implements very rudimentary colorized output. */ static int color_printer( const git_diff_delta *delta, const git_diff_hunk *hunk, const git_diff_line *line, void *data) { int *last_color = data, color = 0; (void)delta; (void)hunk; if (*last_color >= 0) { switch (line->origin) { case GIT_DIFF_LINE_ADDITION: color = 3; break; case GIT_DIFF_LINE_DELETION: color = 2; break; case GIT_DIFF_LINE_ADD_EOFNL: color = 3; break; case GIT_DIFF_LINE_DEL_EOFNL: color = 2; break; case GIT_DIFF_LINE_FILE_HDR: color = 1; break; case GIT_DIFF_LINE_HUNK_HDR: color = 4; break; default: break; } if (color != *last_color) { if (*last_color == 1 || color == 1) fputs(colors[0], stdout); fputs(colors[color], stdout); *last_color = color; } } return diff_output(delta, hunk, line, stdout); } /** Parse arguments as copied from git-diff. */ static void parse_opts(struct diff_options *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *a = argv[args.pos]; if (a[0] != '-') { if (o->treeish1 == NULL) o->treeish1 = a; else if (o->treeish2 == NULL) o->treeish2 = a; else usage("Only one or two tree identifiers can be provided", NULL); } else if (!strcmp(a, "-p") || !strcmp(a, "-u") || !strcmp(a, "--patch")) { o->output |= OUTPUT_DIFF; o->format = GIT_DIFF_FORMAT_PATCH; } else if (!strcmp(a, "--cached")) { o->cache = CACHE_ONLY; if (o->no_index >= 0) usage("--cached and --no-index are incompatible", NULL); } else if (!strcmp(a, "--nocache")) o->cache = CACHE_NONE; else if (!strcmp(a, "--name-only") || !strcmp(a, "--format=name")) o->format = GIT_DIFF_FORMAT_NAME_ONLY; else if (!strcmp(a, "--name-status") || !strcmp(a, "--format=name-status")) o->format = GIT_DIFF_FORMAT_NAME_STATUS; else if (!strcmp(a, "--raw") || !strcmp(a, "--format=raw")) o->format = GIT_DIFF_FORMAT_RAW; else if (!strcmp(a, "--format=diff-index")) { o->format = GIT_DIFF_FORMAT_RAW; o->diffopts.id_abbrev = 40; } else if (!strcmp(a, "--no-index")) { o->no_index = 0; if (o->cache == CACHE_ONLY) usage("--cached and --no-index are incompatible", NULL); } else if (!strcmp(a, "--color")) o->color = 0; else if (!strcmp(a, "--no-color")) o->color = -1; else if (!strcmp(a, "-R")) o->diffopts.flags |= GIT_DIFF_REVERSE; else if (!strcmp(a, "-a") || !strcmp(a, "--text")) o->diffopts.flags |= GIT_DIFF_FORCE_TEXT; else if (!strcmp(a, "--ignore-space-at-eol")) o->diffopts.flags |= GIT_DIFF_IGNORE_WHITESPACE_EOL; else if (!strcmp(a, "-b") || !strcmp(a, "--ignore-space-change")) o->diffopts.flags |= GIT_DIFF_IGNORE_WHITESPACE_CHANGE; else if (!strcmp(a, "-w") || !strcmp(a, "--ignore-all-space")) o->diffopts.flags |= GIT_DIFF_IGNORE_WHITESPACE; else if (!strcmp(a, "--ignored")) o->diffopts.flags |= GIT_DIFF_INCLUDE_IGNORED; else if (!strcmp(a, "--untracked")) o->diffopts.flags |= GIT_DIFF_INCLUDE_UNTRACKED; else if (!strcmp(a, "--patience")) o->diffopts.flags |= GIT_DIFF_PATIENCE; else if (!strcmp(a, "--minimal")) o->diffopts.flags |= GIT_DIFF_MINIMAL; else if (!strcmp(a, "--stat")) o->output |= OUTPUT_STAT; else if (!strcmp(a, "--numstat")) o->output |= OUTPUT_NUMSTAT; else if (!strcmp(a, "--shortstat")) o->output |= OUTPUT_SHORTSTAT; else if (!strcmp(a, "--summary")) o->output |= OUTPUT_SUMMARY; else if (match_uint16_arg( &o->findopts.rename_threshold, &args, "-M") || match_uint16_arg( &o->findopts.rename_threshold, &args, "--find-renames")) o->findopts.flags |= GIT_DIFF_FIND_RENAMES; else if (match_uint16_arg( &o->findopts.copy_threshold, &args, "-C") || match_uint16_arg( &o->findopts.copy_threshold, &args, "--find-copies")) o->findopts.flags |= GIT_DIFF_FIND_COPIES; else if (!strcmp(a, "--find-copies-harder")) o->findopts.flags |= GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; else if (is_prefixed(a, "-B") || is_prefixed(a, "--break-rewrites")) /* TODO: parse thresholds */ o->findopts.flags |= GIT_DIFF_FIND_REWRITES; else if (!match_uint32_arg( &o->diffopts.context_lines, &args, "-U") && !match_uint32_arg( &o->diffopts.context_lines, &args, "--unified") && !match_uint32_arg( &o->diffopts.interhunk_lines, &args, "--inter-hunk-context") && !match_uint16_arg( &o->diffopts.id_abbrev, &args, "--abbrev") && !match_str_arg(&o->diffopts.old_prefix, &args, "--src-prefix") && !match_str_arg(&o->diffopts.new_prefix, &args, "--dst-prefix") && !match_str_arg(&o->dir, &args, "--git-dir")) usage("Unknown command line argument", a); } } /** Display diff output with "--stat", "--numstat", or "--shortstat" */ static void diff_print_stats(git_diff *diff, struct diff_options *o) { git_diff_stats *stats; git_buf b = GIT_BUF_INIT; git_diff_stats_format_t format = 0; check_lg2( git_diff_get_stats(&stats, diff), "generating stats for diff", NULL); if (o->output & OUTPUT_STAT) format |= GIT_DIFF_STATS_FULL; if (o->output & OUTPUT_SHORTSTAT) format |= GIT_DIFF_STATS_SHORT; if (o->output & OUTPUT_NUMSTAT) format |= GIT_DIFF_STATS_NUMBER; if (o->output & OUTPUT_SUMMARY) format |= GIT_DIFF_STATS_INCLUDE_SUMMARY; check_lg2( git_diff_stats_to_buf(&b, stats, format, 80), "formatting stats", NULL); fputs(b.ptr, stdout); git_buf_dispose(&b); git_diff_stats_free(stats); }
libgit2-main
examples/diff.c
/* * Utilities library for libgit2 examples * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" #ifndef _WIN32 # include <unistd.h> #endif #include <errno.h> void check_lg2(int error, const char *message, const char *extra) { const git_error *lg2err; const char *lg2msg = "", *lg2spacer = ""; if (!error) return; if ((lg2err = git_error_last()) != NULL && lg2err->message != NULL) { lg2msg = lg2err->message; lg2spacer = " - "; } if (extra) fprintf(stderr, "%s '%s' [%d]%s%s\n", message, extra, error, lg2spacer, lg2msg); else fprintf(stderr, "%s [%d]%s%s\n", message, error, lg2spacer, lg2msg); exit(1); } void fatal(const char *message, const char *extra) { if (extra) fprintf(stderr, "%s %s\n", message, extra); else fprintf(stderr, "%s\n", message); exit(1); } int diff_output( const git_diff_delta *d, const git_diff_hunk *h, const git_diff_line *l, void *p) { FILE *fp = (FILE*)p; (void)d; (void)h; if (!fp) fp = stdout; if (l->origin == GIT_DIFF_LINE_CONTEXT || l->origin == GIT_DIFF_LINE_ADDITION || l->origin == GIT_DIFF_LINE_DELETION) fputc(l->origin, fp); fwrite(l->content, 1, l->content_len, fp); return 0; } void treeish_to_tree( git_tree **out, git_repository *repo, const char *treeish) { git_object *obj = NULL; check_lg2( git_revparse_single(&obj, repo, treeish), "looking up object", treeish); check_lg2( git_object_peel((git_object **)out, obj, GIT_OBJECT_TREE), "resolving object to tree", treeish); git_object_free(obj); } void *xrealloc(void *oldp, size_t newsz) { void *p = realloc(oldp, newsz); if (p == NULL) { fprintf(stderr, "Cannot allocate memory, exiting.\n"); exit(1); } return p; } int resolve_refish(git_annotated_commit **commit, git_repository *repo, const char *refish) { git_reference *ref; git_object *obj; int err = 0; assert(commit != NULL); err = git_reference_dwim(&ref, repo, refish); if (err == GIT_OK) { git_annotated_commit_from_ref(commit, repo, ref); git_reference_free(ref); return 0; } err = git_revparse_single(&obj, repo, refish); if (err == GIT_OK) { err = git_annotated_commit_lookup(commit, repo, git_object_id(obj)); git_object_free(obj); } return err; } static int readline(char **out) { int c, error = 0, length = 0, allocated = 0; char *line = NULL; errno = 0; while ((c = getchar()) != EOF) { if (length == allocated) { allocated += 16; if ((line = realloc(line, allocated)) == NULL) { error = -1; goto error; } } if (c == '\n') break; line[length++] = c; } if (errno != 0) { error = -1; goto error; } line[length] = '\0'; *out = line; line = NULL; error = length; error: free(line); return error; } static int ask(char **out, const char *prompt, char optional) { printf("%s ", prompt); fflush(stdout); if (!readline(out) && !optional) { fprintf(stderr, "Could not read response: %s", strerror(errno)); return -1; } return 0; } int cred_acquire_cb(git_credential **out, const char *url, const char *username_from_url, unsigned int allowed_types, void *payload) { char *username = NULL, *password = NULL, *privkey = NULL, *pubkey = NULL; int error = 1; UNUSED(url); UNUSED(payload); if (username_from_url) { if ((username = strdup(username_from_url)) == NULL) goto out; } else if ((error = ask(&username, "Username:", 0)) < 0) { goto out; } if (allowed_types & GIT_CREDENTIAL_SSH_KEY) { int n; if ((error = ask(&privkey, "SSH Key:", 0)) < 0 || (error = ask(&password, "Password:", 1)) < 0) goto out; if ((n = snprintf(NULL, 0, "%s.pub", privkey)) < 0 || (pubkey = malloc(n + 1)) == NULL || (n = snprintf(pubkey, n + 1, "%s.pub", privkey)) < 0) goto out; error = git_credential_ssh_key_new(out, username, pubkey, privkey, password); } else if (allowed_types & GIT_CREDENTIAL_USERPASS_PLAINTEXT) { if ((error = ask(&password, "Password:", 1)) < 0) goto out; error = git_credential_userpass_plaintext_new(out, username, password); } else if (allowed_types & GIT_CREDENTIAL_USERNAME) { error = git_credential_username_new(out, username); } out: free(username); free(password); free(privkey); free(pubkey); return error; } char *read_file(const char *path) { ssize_t total = 0; char *buf = NULL; struct stat st; int fd = -1; if ((fd = open(path, O_RDONLY)) < 0 || fstat(fd, &st) < 0) goto out; if ((buf = malloc(st.st_size + 1)) == NULL) goto out; while (total < st.st_size) { ssize_t bytes = read(fd, buf + total, st.st_size - total); if (bytes <= 0) { if (errno == EAGAIN || errno == EINTR) continue; free(buf); buf = NULL; goto out; } total += bytes; } buf[total] = '\0'; out: if (fd >= 0) close(fd); return buf; }
libgit2-main
examples/common.c
#include "common.h" static int progress_cb(const char *str, int len, void *data) { (void)data; printf("remote: %.*s", len, str); fflush(stdout); /* We don't have the \n to force the flush */ return 0; } /** * This function gets called for each remote-tracking branch that gets * updated. The message we output depends on whether it's a new one or * an update. */ static int update_cb(const char *refname, const git_oid *a, const git_oid *b, void *data) { char a_str[GIT_OID_SHA1_HEXSIZE+1], b_str[GIT_OID_SHA1_HEXSIZE+1]; (void)data; git_oid_fmt(b_str, b); b_str[GIT_OID_SHA1_HEXSIZE] = '\0'; if (git_oid_is_zero(a)) { printf("[new] %.20s %s\n", b_str, refname); } else { git_oid_fmt(a_str, a); a_str[GIT_OID_SHA1_HEXSIZE] = '\0'; printf("[updated] %.10s..%.10s %s\n", a_str, b_str, refname); } return 0; } /** * This gets called during the download and indexing. Here we show * processed and total objects in the pack and the amount of received * data. Most frontends will probably want to show a percentage and * the download rate. */ static int transfer_progress_cb(const git_indexer_progress *stats, void *payload) { (void)payload; if (stats->received_objects == stats->total_objects) { printf("Resolving deltas %u/%u\r", stats->indexed_deltas, stats->total_deltas); } else if (stats->total_objects > 0) { printf("Received %u/%u objects (%u) in %" PRIuZ " bytes\r", stats->received_objects, stats->total_objects, stats->indexed_objects, stats->received_bytes); } return 0; } /** Entry point for this command */ int lg2_fetch(git_repository *repo, int argc, char **argv) { git_remote *remote = NULL; const git_indexer_progress *stats; git_fetch_options fetch_opts = GIT_FETCH_OPTIONS_INIT; if (argc < 2) { fprintf(stderr, "usage: %s fetch <repo>\n", argv[-1]); return EXIT_FAILURE; } /* Figure out whether it's a named remote or a URL */ printf("Fetching %s for repo %p\n", argv[1], repo); if (git_remote_lookup(&remote, repo, argv[1]) < 0) if (git_remote_create_anonymous(&remote, repo, argv[1]) < 0) goto on_error; /* Set up the callbacks (only update_tips for now) */ fetch_opts.callbacks.update_tips = &update_cb; fetch_opts.callbacks.sideband_progress = &progress_cb; fetch_opts.callbacks.transfer_progress = transfer_progress_cb; fetch_opts.callbacks.credentials = cred_acquire_cb; /** * Perform the fetch with the configured refspecs from the * config. Update the reflog for the updated references with * "fetch". */ if (git_remote_fetch(remote, NULL, &fetch_opts, "fetch") < 0) goto on_error; /** * If there are local objects (we got a thin pack), then tell * the user how many objects we saved from having to cross the * network. */ stats = git_remote_stats(remote); if (stats->local_objects > 0) { printf("\rReceived %u/%u objects in %" PRIuZ " bytes (used %u local objects)\n", stats->indexed_objects, stats->total_objects, stats->received_bytes, stats->local_objects); } else{ printf("\rReceived %u/%u objects in %" PRIuZ "bytes\n", stats->indexed_objects, stats->total_objects, stats->received_bytes); } git_remote_free(remote); return 0; on_error: git_remote_free(remote); return -1; }
libgit2-main
examples/fetch.c
#include "common.h" #include "args.h" size_t is_prefixed(const char *str, const char *pfx) { size_t len = strlen(pfx); return strncmp(str, pfx, len) ? 0 : len; } int optional_str_arg( const char **out, struct args_info *args, const char *opt, const char *def) { const char *found = args->argv[args->pos]; size_t len = is_prefixed(found, opt); if (!len) return 0; if (!found[len]) { if (args->pos + 1 == args->argc) { *out = def; return 1; } args->pos += 1; *out = args->argv[args->pos]; return 1; } if (found[len] == '=') { *out = found + len + 1; return 1; } return 0; } int match_str_arg( const char **out, struct args_info *args, const char *opt) { const char *found = args->argv[args->pos]; size_t len = is_prefixed(found, opt); if (!len) return 0; if (!found[len]) { if (args->pos + 1 == args->argc) fatal("expected value following argument", opt); args->pos += 1; *out = args->argv[args->pos]; return 1; } if (found[len] == '=') { *out = found + len + 1; return 1; } return 0; } static const char *match_numeric_arg(struct args_info *args, const char *opt) { const char *found = args->argv[args->pos]; size_t len = is_prefixed(found, opt); if (!len) return NULL; if (!found[len]) { if (args->pos + 1 == args->argc) fatal("expected numeric value following argument", opt); args->pos += 1; found = args->argv[args->pos]; } else { found = found + len; if (*found == '=') found++; } return found; } int match_uint16_arg( uint16_t *out, struct args_info *args, const char *opt) { const char *found = match_numeric_arg(args, opt); uint16_t val; char *endptr = NULL; if (!found) return 0; val = (uint16_t)strtoul(found, &endptr, 0); if (!endptr || *endptr != '\0') fatal("expected number after argument", opt); if (out) *out = val; return 1; } int match_uint32_arg( uint32_t *out, struct args_info *args, const char *opt) { const char *found = match_numeric_arg(args, opt); uint16_t val; char *endptr = NULL; if (!found) return 0; val = (uint32_t)strtoul(found, &endptr, 0); if (!endptr || *endptr != '\0') fatal("expected number after argument", opt); if (out) *out = val; return 1; } static int match_int_internal( int *out, const char *str, int allow_negative, const char *opt) { char *endptr = NULL; int val = (int)strtol(str, &endptr, 10); if (!endptr || *endptr != '\0') fatal("expected number", opt); else if (val < 0 && !allow_negative) fatal("negative values are not allowed", opt); if (out) *out = val; return 1; } int match_bool_arg(int *out, struct args_info *args, const char *opt) { const char *found = args->argv[args->pos]; if (!strcmp(found, opt)) { *out = 1; return 1; } if (!strncmp(found, "--no-", strlen("--no-")) && !strcmp(found + strlen("--no-"), opt + 2)) { *out = 0; return 1; } *out = -1; return 0; } int is_integer(int *out, const char *str, int allow_negative) { return match_int_internal(out, str, allow_negative, NULL); } int match_int_arg( int *out, struct args_info *args, const char *opt, int allow_negative) { const char *found = match_numeric_arg(args, opt); if (!found) return 0; return match_int_internal(out, found, allow_negative, opt); } int match_arg_separator(struct args_info *args) { if (args->opts_done) return 1; if (strcmp(args->argv[args->pos], "--") != 0) return 0; args->opts_done = 1; args->pos++; return 1; } void strarray_from_args(git_strarray *array, struct args_info *args) { size_t i; array->count = args->argc - args->pos; array->strings = calloc(array->count, sizeof(char *)); assert(array->strings != NULL); for (i = 0; args->pos < args->argc; ++args->pos) { array->strings[i++] = args->argv[args->pos]; } args->pos = args->argc; }
libgit2-main
examples/args.c
/* * libgit2 "remote" example - shows how to modify remotes for a repo * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This is a sample program that is similar to "git remote". See the * documentation for that (try "git help remote") to understand what this * program is emulating. * * This demonstrates using the libgit2 APIs to modify remotes of a repository. */ enum subcmd { subcmd_add, subcmd_remove, subcmd_rename, subcmd_seturl, subcmd_show }; struct remote_opts { enum subcmd cmd; /* for command-specific args */ int argc; char **argv; }; static int cmd_add(git_repository *repo, struct remote_opts *o); static int cmd_remove(git_repository *repo, struct remote_opts *o); static int cmd_rename(git_repository *repo, struct remote_opts *o); static int cmd_seturl(git_repository *repo, struct remote_opts *o); static int cmd_show(git_repository *repo, struct remote_opts *o); static void parse_subcmd( struct remote_opts *opt, int argc, char **argv); static void usage(const char *msg, const char *arg); int lg2_remote(git_repository *repo, int argc, char *argv[]) { int retval = 0; struct remote_opts opt = {0}; parse_subcmd(&opt, argc, argv); switch (opt.cmd) { case subcmd_add: retval = cmd_add(repo, &opt); break; case subcmd_remove: retval = cmd_remove(repo, &opt); break; case subcmd_rename: retval = cmd_rename(repo, &opt); break; case subcmd_seturl: retval = cmd_seturl(repo, &opt); break; case subcmd_show: retval = cmd_show(repo, &opt); break; } return retval; } static int cmd_add(git_repository *repo, struct remote_opts *o) { char *name, *url; git_remote *remote = {0}; if (o->argc != 2) usage("you need to specify a name and URL", NULL); name = o->argv[0]; url = o->argv[1]; check_lg2(git_remote_create(&remote, repo, name, url), "could not create remote", NULL); return 0; } static int cmd_remove(git_repository *repo, struct remote_opts *o) { char *name; if (o->argc != 1) usage("you need to specify a name", NULL); name = o->argv[0]; check_lg2(git_remote_delete(repo, name), "could not delete remote", name); return 0; } static int cmd_rename(git_repository *repo, struct remote_opts *o) { int i, retval; char *old, *new; git_strarray problems = {0}; if (o->argc != 2) usage("you need to specify old and new remote name", NULL); old = o->argv[0]; new = o->argv[1]; retval = git_remote_rename(&problems, repo, old, new); if (!retval) return 0; for (i = 0; i < (int) problems.count; i++) { puts(problems.strings[0]); } git_strarray_dispose(&problems); return retval; } static int cmd_seturl(git_repository *repo, struct remote_opts *o) { int i, retval, push = 0; char *name = NULL, *url = NULL; for (i = 0; i < o->argc; i++) { char *arg = o->argv[i]; if (!strcmp(arg, "--push")) { push = 1; } else if (arg[0] != '-' && name == NULL) { name = arg; } else if (arg[0] != '-' && url == NULL) { url = arg; } else { usage("invalid argument to set-url", arg); } } if (name == NULL || url == NULL) usage("you need to specify remote and the new URL", NULL); if (push) retval = git_remote_set_pushurl(repo, name, url); else retval = git_remote_set_url(repo, name, url); check_lg2(retval, "could not set URL", url); return 0; } static int cmd_show(git_repository *repo, struct remote_opts *o) { int i; const char *arg, *name, *fetch, *push; int verbose = 0; git_strarray remotes = {0}; git_remote *remote = {0}; for (i = 0; i < o->argc; i++) { arg = o->argv[i]; if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) { verbose = 1; } } check_lg2(git_remote_list(&remotes, repo), "could not retrieve remotes", NULL); for (i = 0; i < (int) remotes.count; i++) { name = remotes.strings[i]; if (!verbose) { puts(name); continue; } check_lg2(git_remote_lookup(&remote, repo, name), "could not look up remote", name); fetch = git_remote_url(remote); if (fetch) printf("%s\t%s (fetch)\n", name, fetch); push = git_remote_pushurl(remote); /* use fetch URL if no distinct push URL has been set */ push = push ? push : fetch; if (push) printf("%s\t%s (push)\n", name, push); git_remote_free(remote); } git_strarray_dispose(&remotes); return 0; } static void parse_subcmd( struct remote_opts *opt, int argc, char **argv) { char *arg = argv[1]; enum subcmd cmd = 0; if (argc < 2) usage("no command specified", NULL); if (!strcmp(arg, "add")) { cmd = subcmd_add; } else if (!strcmp(arg, "remove")) { cmd = subcmd_remove; } else if (!strcmp(arg, "rename")) { cmd = subcmd_rename; } else if (!strcmp(arg, "set-url")) { cmd = subcmd_seturl; } else if (!strcmp(arg, "show")) { cmd = subcmd_show; } else { usage("command is not valid", arg); } opt->cmd = cmd; opt->argc = argc - 2; /* executable and subcommand are removed */ opt->argv = argv + 2; } static void usage(const char *msg, const char *arg) { fputs("usage: remote add <name> <url>\n", stderr); fputs(" remote remove <name>\n", stderr); fputs(" remote rename <old> <new>\n", stderr); fputs(" remote set-url [--push] <name> <newurl>\n", stderr); fputs(" remote show [-v|--verbose]\n", stderr); if (msg && !arg) fprintf(stderr, "\n%s\n", msg); else if (msg && arg) fprintf(stderr, "\n%s: %s\n", msg, arg); exit(1); }
libgit2-main
examples/remote.c
#include <git2.h> #include "common.h" static int show_ref(git_reference *ref, void *data) { git_repository *repo = data; git_reference *resolved = NULL; char hex[GIT_OID_SHA1_HEXSIZE+1]; const git_oid *oid; git_object *obj; if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) check_lg2(git_reference_resolve(&resolved, ref), "Unable to resolve symbolic reference", git_reference_name(ref)); oid = git_reference_target(resolved ? resolved : ref); git_oid_fmt(hex, oid); hex[GIT_OID_SHA1_HEXSIZE] = 0; check_lg2(git_object_lookup(&obj, repo, oid, GIT_OBJECT_ANY), "Unable to lookup object", hex); printf("%s %-6s\t%s\n", hex, git_object_type2string(git_object_type(obj)), git_reference_name(ref)); if (resolved) git_reference_free(resolved); return 0; } int lg2_for_each_ref(git_repository *repo, int argc, char **argv) { UNUSED(argv); if (argc != 1) fatal("Sorry, no for-each-ref options supported yet", NULL); check_lg2(git_reference_foreach(repo, show_ref, repo), "Could not iterate over references", NULL); return 0; }
libgit2-main
examples/for-each-ref.c
/* * libgit2 "cat-file" example - shows how to print data from the ODB * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" static void print_signature(const char *header, const git_signature *sig) { char sign; int offset, hours, minutes; if (!sig) return; offset = sig->when.offset; if (offset < 0) { sign = '-'; offset = -offset; } else { sign = '+'; } hours = offset / 60; minutes = offset % 60; printf("%s %s <%s> %ld %c%02d%02d\n", header, sig->name, sig->email, (long)sig->when.time, sign, hours, minutes); } /** Printing out a blob is simple, get the contents and print */ static void show_blob(const git_blob *blob) { /* ? Does this need crlf filtering? */ fwrite(git_blob_rawcontent(blob), (size_t)git_blob_rawsize(blob), 1, stdout); } /** Show each entry with its type, id and attributes */ static void show_tree(const git_tree *tree) { size_t i, max_i = (int)git_tree_entrycount(tree); char oidstr[GIT_OID_SHA1_HEXSIZE + 1]; const git_tree_entry *te; for (i = 0; i < max_i; ++i) { te = git_tree_entry_byindex(tree, i); git_oid_tostr(oidstr, sizeof(oidstr), git_tree_entry_id(te)); printf("%06o %s %s\t%s\n", git_tree_entry_filemode(te), git_object_type2string(git_tree_entry_type(te)), oidstr, git_tree_entry_name(te)); } } /** * Commits and tags have a few interesting fields in their header. */ static void show_commit(const git_commit *commit) { unsigned int i, max_i; char oidstr[GIT_OID_SHA1_HEXSIZE + 1]; git_oid_tostr(oidstr, sizeof(oidstr), git_commit_tree_id(commit)); printf("tree %s\n", oidstr); max_i = (unsigned int)git_commit_parentcount(commit); for (i = 0; i < max_i; ++i) { git_oid_tostr(oidstr, sizeof(oidstr), git_commit_parent_id(commit, i)); printf("parent %s\n", oidstr); } print_signature("author", git_commit_author(commit)); print_signature("committer", git_commit_committer(commit)); if (git_commit_message(commit)) printf("\n%s\n", git_commit_message(commit)); } static void show_tag(const git_tag *tag) { char oidstr[GIT_OID_SHA1_HEXSIZE + 1]; git_oid_tostr(oidstr, sizeof(oidstr), git_tag_target_id(tag));; printf("object %s\n", oidstr); printf("type %s\n", git_object_type2string(git_tag_target_type(tag))); printf("tag %s\n", git_tag_name(tag)); print_signature("tagger", git_tag_tagger(tag)); if (git_tag_message(tag)) printf("\n%s\n", git_tag_message(tag)); } typedef enum { SHOW_TYPE = 1, SHOW_SIZE = 2, SHOW_NONE = 3, SHOW_PRETTY = 4 } catfile_mode; /* Forward declarations for option-parsing helper */ struct catfile_options { const char *dir; const char *rev; catfile_mode action; int verbose; }; static void parse_opts(struct catfile_options *o, int argc, char *argv[]); /** Entry point for this command */ int lg2_cat_file(git_repository *repo, int argc, char *argv[]) { struct catfile_options o = { ".", NULL, 0, 0 }; git_object *obj = NULL; char oidstr[GIT_OID_SHA1_HEXSIZE + 1]; parse_opts(&o, argc, argv); check_lg2(git_revparse_single(&obj, repo, o.rev), "Could not resolve", o.rev); if (o.verbose) { char oidstr[GIT_OID_SHA1_HEXSIZE + 1]; git_oid_tostr(oidstr, sizeof(oidstr), git_object_id(obj)); printf("%s %s\n--\n", git_object_type2string(git_object_type(obj)), oidstr); } switch (o.action) { case SHOW_TYPE: printf("%s\n", git_object_type2string(git_object_type(obj))); break; case SHOW_SIZE: { git_odb *odb; git_odb_object *odbobj; check_lg2(git_repository_odb(&odb, repo), "Could not open ODB", NULL); check_lg2(git_odb_read(&odbobj, odb, git_object_id(obj)), "Could not find obj", NULL); printf("%ld\n", (long)git_odb_object_size(odbobj)); git_odb_object_free(odbobj); git_odb_free(odb); } break; case SHOW_NONE: /* just want return result */ break; case SHOW_PRETTY: switch (git_object_type(obj)) { case GIT_OBJECT_BLOB: show_blob((const git_blob *)obj); break; case GIT_OBJECT_COMMIT: show_commit((const git_commit *)obj); break; case GIT_OBJECT_TREE: show_tree((const git_tree *)obj); break; case GIT_OBJECT_TAG: show_tag((const git_tag *)obj); break; default: printf("unknown %s\n", oidstr); break; } break; } git_object_free(obj); return 0; } /** Print out usage information */ static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: cat-file (-t | -s | -e | -p) [-v] [-q] " "[-h|--help] [--git-dir=<dir>] <object>\n"); exit(1); } /** Parse the command-line options taken from git */ static void parse_opts(struct catfile_options *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { char *a = argv[args.pos]; if (a[0] != '-') { if (o->rev != NULL) usage("Only one rev should be provided", NULL); else o->rev = a; } else if (!strcmp(a, "-t")) o->action = SHOW_TYPE; else if (!strcmp(a, "-s")) o->action = SHOW_SIZE; else if (!strcmp(a, "-e")) o->action = SHOW_NONE; else if (!strcmp(a, "-p")) o->action = SHOW_PRETTY; else if (!strcmp(a, "-q")) o->verbose = 0; else if (!strcmp(a, "-v")) o->verbose = 1; else if (!strcmp(a, "--help") || !strcmp(a, "-h")) usage(NULL, NULL); else if (!match_str_arg(&o->dir, &args, "--git-dir")) usage("Unknown option", a); } if (!o->action || !o->rev) usage(NULL, NULL); }
libgit2-main
examples/cat-file.c
/* * libgit2 "push" example - shows how to push to remote * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 push API to roughly * simulate `git push`. * * This does not have: * * - Robust error handling * - Any of the `git push` options * * This does have: * * - Example of push to origin/master * */ /** Entry point for this command */ int lg2_push(git_repository *repo, int argc, char **argv) { git_push_options options; git_remote* remote = NULL; char *refspec = "refs/heads/master"; const git_strarray refspecs = { &refspec, 1 }; /* Validate args */ if (argc > 1) { printf ("USAGE: %s\n\nsorry, no arguments supported yet\n", argv[0]); return -1; } check_lg2(git_remote_lookup(&remote, repo, "origin" ), "Unable to lookup remote", NULL); check_lg2(git_push_options_init(&options, GIT_PUSH_OPTIONS_VERSION ), "Error initializing push", NULL); check_lg2(git_remote_push(remote, &refspecs, &options), "Error pushing", NULL); printf("pushed\n"); return 0; }
libgit2-main
examples/push.c
/* * libgit2 "init" example - shows how to initialize a new repo * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This is a sample program that is similar to "git init". See the * documentation for that (try "git help init") to understand what this * program is emulating. * * This demonstrates using the libgit2 APIs to initialize a new repository. * * This also contains a special additional option that regular "git init" * does not support which is "--initial-commit" to make a first empty commit. * That is demonstrated in the "create_initial_commit" helper function. */ /** Forward declarations of helpers */ struct init_opts { int no_options; int quiet; int bare; int initial_commit; uint32_t shared; const char *template; const char *gitdir; const char *dir; }; static void create_initial_commit(git_repository *repo); static void parse_opts(struct init_opts *o, int argc, char *argv[]); int lg2_init(git_repository *repo, int argc, char *argv[]) { struct init_opts o = { 1, 0, 0, 0, GIT_REPOSITORY_INIT_SHARED_UMASK, 0, 0, 0 }; parse_opts(&o, argc, argv); /* Initialize repository. */ if (o.no_options) { /** * No options were specified, so let's demonstrate the default * simple case of git_repository_init() API usage... */ check_lg2(git_repository_init(&repo, o.dir, 0), "Could not initialize repository", NULL); } else { /** * Some command line options were specified, so we'll use the * extended init API to handle them */ git_repository_init_options initopts = GIT_REPOSITORY_INIT_OPTIONS_INIT; initopts.flags = GIT_REPOSITORY_INIT_MKPATH; if (o.bare) initopts.flags |= GIT_REPOSITORY_INIT_BARE; if (o.template) { initopts.flags |= GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE; initopts.template_path = o.template; } if (o.gitdir) { /** * If you specified a separate git directory, then initialize * the repository at that path and use the second path as the * working directory of the repository (with a git-link file) */ initopts.workdir_path = o.dir; o.dir = o.gitdir; } if (o.shared != 0) initopts.mode = o.shared; check_lg2(git_repository_init_ext(&repo, o.dir, &initopts), "Could not initialize repository", NULL); } /** Print a message to stdout like "git init" does. */ if (!o.quiet) { if (o.bare || o.gitdir) o.dir = git_repository_path(repo); else o.dir = git_repository_workdir(repo); printf("Initialized empty Git repository in %s\n", o.dir); } /** * As an extension to the basic "git init" command, this example * gives the option to create an empty initial commit. This is * mostly to demonstrate what it takes to do that, but also some * people like to have that empty base commit in their repo. */ if (o.initial_commit) { create_initial_commit(repo); printf("Created empty initial commit\n"); } git_repository_free(repo); return 0; } /** * Unlike regular "git init", this example shows how to create an initial * empty commit in the repository. This is the helper function that does * that. */ static void create_initial_commit(git_repository *repo) { git_signature *sig; git_index *index; git_oid tree_id, commit_id; git_tree *tree; /** First use the config to initialize a commit signature for the user. */ if (git_signature_default(&sig, repo) < 0) fatal("Unable to create a commit signature.", "Perhaps 'user.name' and 'user.email' are not set"); /* Now let's create an empty tree for this commit */ if (git_repository_index(&index, repo) < 0) fatal("Could not open repository index", NULL); /** * Outside of this example, you could call git_index_add_bypath() * here to put actual files into the index. For our purposes, we'll * leave it empty for now. */ if (git_index_write_tree(&tree_id, index) < 0) fatal("Unable to write initial tree from index", NULL); git_index_free(index); if (git_tree_lookup(&tree, repo, &tree_id) < 0) fatal("Could not look up initial tree", NULL); /** * Ready to create the initial commit. * * Normally creating a commit would involve looking up the current * HEAD commit and making that be the parent of the initial commit, * but here this is the first commit so there will be no parent. */ if (git_commit_create_v( &commit_id, repo, "HEAD", sig, sig, NULL, "Initial commit", tree, 0) < 0) fatal("Could not create the initial commit", NULL); /** Clean up so we don't leak memory. */ git_tree_free(tree); git_signature_free(sig); } static void usage(const char *error, const char *arg) { fprintf(stderr, "error: %s '%s'\n", error, arg); fprintf(stderr, "usage: init [-q | --quiet] [--bare] [--template=<dir>]\n" " [--shared[=perms]] [--initial-commit]\n" " [--separate-git-dir] <directory>\n"); exit(1); } /** Parse the tail of the --shared= argument. */ static uint32_t parse_shared(const char *shared) { if (!strcmp(shared, "false") || !strcmp(shared, "umask")) return GIT_REPOSITORY_INIT_SHARED_UMASK; else if (!strcmp(shared, "true") || !strcmp(shared, "group")) return GIT_REPOSITORY_INIT_SHARED_GROUP; else if (!strcmp(shared, "all") || !strcmp(shared, "world") || !strcmp(shared, "everybody")) return GIT_REPOSITORY_INIT_SHARED_ALL; else if (shared[0] == '0') { long val; char *end = NULL; val = strtol(shared + 1, &end, 8); if (end == shared + 1 || *end != 0) usage("invalid octal value for --shared", shared); return (uint32_t)val; } else usage("unknown value for --shared", shared); return 0; } static void parse_opts(struct init_opts *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; const char *sharedarg; /** Process arguments. */ for (args.pos = 1; args.pos < argc; ++args.pos) { char *a = argv[args.pos]; if (a[0] == '-') o->no_options = 0; if (a[0] != '-') { if (o->dir != NULL) usage("extra argument", a); o->dir = a; } else if (!strcmp(a, "-q") || !strcmp(a, "--quiet")) o->quiet = 1; else if (!strcmp(a, "--bare")) o->bare = 1; else if (!strcmp(a, "--shared")) o->shared = GIT_REPOSITORY_INIT_SHARED_GROUP; else if (!strcmp(a, "--initial-commit")) o->initial_commit = 1; else if (match_str_arg(&sharedarg, &args, "--shared")) o->shared = parse_shared(sharedarg); else if (!match_str_arg(&o->template, &args, "--template") || !match_str_arg(&o->gitdir, &args, "--separate-git-dir")) usage("unknown option", a); } if (!o->dir) usage("must specify directory to init", ""); }
libgit2-main
examples/init.c
/* * libgit2 "ls-files" example - shows how to view all files currently in the index * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 index APIs to roughly * simulate the output of `git ls-files`. * `git ls-files` has many options and this currently does not show them. * * `git ls-files` base command shows all paths in the index at that time. * This includes staged and committed files, but unstaged files will not display. * * This currently supports the default behavior and the `--error-unmatch` option. */ struct ls_options { int error_unmatch; char *files[1024]; size_t file_count; }; static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: ls-files [--error-unmatch] [--] [<file>...]\n"); exit(1); } static int parse_options(struct ls_options *opts, int argc, char *argv[]) { int parsing_files = 0; int i; memset(opts, 0, sizeof(struct ls_options)); if (argc < 2) return 0; for (i = 1; i < argc; ++i) { char *a = argv[i]; /* if it doesn't start with a '-' or is after the '--' then it is a file */ if (a[0] != '-' || parsing_files) { parsing_files = 1; /* watch for overflows (just in case) */ if (opts->file_count == 1024) { fprintf(stderr, "ls-files can only support 1024 files at this time.\n"); return -1; } opts->files[opts->file_count++] = a; } else if (!strcmp(a, "--")) { parsing_files = 1; } else if (!strcmp(a, "--error-unmatch")) { opts->error_unmatch = 1; } else { usage("Unsupported argument", a); return -1; } } return 0; } static int print_paths(struct ls_options *opts, git_index *index) { size_t i; const git_index_entry *entry; /* if there are no files explicitly listed by the user print all entries in the index */ if (opts->file_count == 0) { size_t entry_count = git_index_entrycount(index); for (i = 0; i < entry_count; i++) { entry = git_index_get_byindex(index, i); puts(entry->path); } return 0; } /* loop through the files found in the args and print them if they exist */ for (i = 0; i < opts->file_count; ++i) { const char *path = opts->files[i]; if ((entry = git_index_get_bypath(index, path, GIT_INDEX_STAGE_NORMAL)) != NULL) { puts(path); } else if (opts->error_unmatch) { fprintf(stderr, "error: pathspec '%s' did not match any file(s) known to git.\n", path); fprintf(stderr, "Did you forget to 'git add'?\n"); return -1; } } return 0; } int lg2_ls_files(git_repository *repo, int argc, char *argv[]) { git_index *index = NULL; struct ls_options opts; int error; if ((error = parse_options(&opts, argc, argv)) < 0) return error; if ((error = git_repository_index(&index, repo)) < 0) goto cleanup; error = print_paths(&opts, index); cleanup: git_index_free(index); return error; }
libgit2-main
examples/ls-files.c
/* * libgit2 "rev-parse" example - shows how to parse revspecs * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** Forward declarations for helpers. */ struct parse_state { const char *repodir; const char *spec; int not; }; static void parse_opts(struct parse_state *ps, int argc, char *argv[]); static int parse_revision(git_repository *repo, struct parse_state *ps); int lg2_rev_parse(git_repository *repo, int argc, char *argv[]) { struct parse_state ps = {0}; parse_opts(&ps, argc, argv); check_lg2(parse_revision(repo, &ps), "Parsing", NULL); return 0; } static void usage(const char *message, const char *arg) { if (message && arg) fprintf(stderr, "%s: %s\n", message, arg); else if (message) fprintf(stderr, "%s\n", message); fprintf(stderr, "usage: rev-parse [ --option ] <args>...\n"); exit(1); } static void parse_opts(struct parse_state *ps, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos=1; args.pos < argc; ++args.pos) { const char *a = argv[args.pos]; if (a[0] != '-') { if (ps->spec) usage("Too many specs", a); ps->spec = a; } else if (!strcmp(a, "--not")) ps->not = !ps->not; else if (!match_str_arg(&ps->repodir, &args, "--git-dir")) usage("Cannot handle argument", a); } } static int parse_revision(git_repository *repo, struct parse_state *ps) { git_revspec rs; char str[GIT_OID_SHA1_HEXSIZE + 1]; check_lg2(git_revparse(&rs, repo, ps->spec), "Could not parse", ps->spec); if ((rs.flags & GIT_REVSPEC_SINGLE) != 0) { git_oid_tostr(str, sizeof(str), git_object_id(rs.from)); printf("%s\n", str); git_object_free(rs.from); } else if ((rs.flags & GIT_REVSPEC_RANGE) != 0) { git_oid_tostr(str, sizeof(str), git_object_id(rs.to)); printf("%s\n", str); git_object_free(rs.to); if ((rs.flags & GIT_REVSPEC_MERGE_BASE) != 0) { git_oid base; check_lg2(git_merge_base(&base, repo, git_object_id(rs.from), git_object_id(rs.to)), "Could not find merge base", ps->spec); git_oid_tostr(str, sizeof(str), &base); printf("%s\n", str); } git_oid_tostr(str, sizeof(str), git_object_id(rs.from)); printf("^%s\n", str); git_object_free(rs.from); } else { fatal("Invalid results from git_revparse", ps->spec); } return 0; }
libgit2-main
examples/rev-parse.c
/* * libgit2 "checkout" example - shows how to perform checkouts * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /* Define the printf format specifier to use for size_t output */ #if defined(_MSC_VER) || defined(__MINGW32__) # define PRIuZ "Iu" # define PRIxZ "Ix" # define PRIdZ "Id" #else # define PRIuZ "zu" # define PRIxZ "zx" # define PRIdZ "zd" #endif /** * The following example demonstrates how to do checkouts with libgit2. * * Recognized options are : * --force: force the checkout to happen. * --[no-]progress: show checkout progress, on by default. * --perf: show performance data. */ typedef struct { int force : 1; int progress : 1; int perf : 1; } checkout_options; static void print_usage(void) { fprintf(stderr, "usage: checkout [options] <branch>\n" "Options are :\n" " --git-dir: use the following git repository.\n" " --force: force the checkout.\n" " --[no-]progress: show checkout progress.\n" " --perf: show performance data.\n"); exit(1); } static void parse_options(const char **repo_path, checkout_options *opts, struct args_info *args) { if (args->argc <= 1) print_usage(); memset(opts, 0, sizeof(*opts)); /* Default values */ opts->progress = 1; for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; int bool_arg; if (match_arg_separator(args)) { break; } else if (!strcmp(curr, "--force")) { opts->force = 1; } else if (match_bool_arg(&bool_arg, args, "--progress")) { opts->progress = bool_arg; } else if (match_bool_arg(&bool_arg, args, "--perf")) { opts->perf = bool_arg; } else if (match_str_arg(repo_path, args, "--git-dir")) { continue; } else { break; } } } /** * This function is called to report progression, ie. it's called once with * a NULL path and the number of total steps, then for each subsequent path, * the current completed_step value. */ static void print_checkout_progress(const char *path, size_t completed_steps, size_t total_steps, void *payload) { (void)payload; if (path == NULL) { printf("checkout started: %" PRIuZ " steps\n", total_steps); } else { printf("checkout: %s %" PRIuZ "/%" PRIuZ "\n", path, completed_steps, total_steps); } } /** * This function is called when the checkout completes, and is used to report the * number of syscalls performed. */ static void print_perf_data(const git_checkout_perfdata *perfdata, void *payload) { (void)payload; printf("perf: stat: %" PRIuZ " mkdir: %" PRIuZ " chmod: %" PRIuZ "\n", perfdata->stat_calls, perfdata->mkdir_calls, perfdata->chmod_calls); } /** * This is the main "checkout <branch>" function, responsible for performing * a branch-based checkout. */ static int perform_checkout_ref(git_repository *repo, git_annotated_commit *target, const char *target_ref, checkout_options *opts) { git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; git_reference *ref = NULL, *branch = NULL; git_commit *target_commit = NULL; int err; /** Setup our checkout options from the parsed options */ checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; if (opts->force) checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; if (opts->progress) checkout_opts.progress_cb = print_checkout_progress; if (opts->perf) checkout_opts.perfdata_cb = print_perf_data; /** Grab the commit we're interested to move to */ err = git_commit_lookup(&target_commit, repo, git_annotated_commit_id(target)); if (err != 0) { fprintf(stderr, "failed to lookup commit: %s\n", git_error_last()->message); goto cleanup; } /** * Perform the checkout so the workdir corresponds to what target_commit * contains. * * Note that it's okay to pass a git_commit here, because it will be * peeled to a tree. */ err = git_checkout_tree(repo, (const git_object *)target_commit, &checkout_opts); if (err != 0) { fprintf(stderr, "failed to checkout tree: %s\n", git_error_last()->message); goto cleanup; } /** * Now that the checkout has completed, we have to update HEAD. * * Depending on the "origin" of target (ie. it's an OID or a branch name), * we might need to detach HEAD. */ if (git_annotated_commit_ref(target)) { const char *target_head; if ((err = git_reference_lookup(&ref, repo, git_annotated_commit_ref(target))) < 0) goto error; if (git_reference_is_remote(ref)) { if ((err = git_branch_create_from_annotated(&branch, repo, target_ref, target, 0)) < 0) goto error; target_head = git_reference_name(branch); } else { target_head = git_annotated_commit_ref(target); } err = git_repository_set_head(repo, target_head); } else { err = git_repository_set_head_detached_from_annotated(repo, target); } error: if (err != 0) { fprintf(stderr, "failed to update HEAD reference: %s\n", git_error_last()->message); goto cleanup; } cleanup: git_commit_free(target_commit); git_reference_free(branch); git_reference_free(ref); return err; } /** * This corresponds to `git switch --guess`: if a given ref does * not exist, git will by default try to guess the reference by * seeing whether any remote has a branch called <ref>. If there * is a single remote only that has it, then it is assumed to be * the desired reference and a local branch is created for it. * * The following is a simplified implementation. It will not try * to check whether the ref is unique across all remotes. */ static int guess_refish(git_annotated_commit **out, git_repository *repo, const char *ref) { git_strarray remotes = { NULL, 0 }; git_reference *remote_ref = NULL; int error; size_t i; if ((error = git_remote_list(&remotes, repo)) < 0) goto out; for (i = 0; i < remotes.count; i++) { char *refname = NULL; size_t reflen; reflen = snprintf(refname, 0, "refs/remotes/%s/%s", remotes.strings[i], ref); if ((refname = malloc(reflen + 1)) == NULL) { error = -1; goto next; } snprintf(refname, reflen + 1, "refs/remotes/%s/%s", remotes.strings[i], ref); if ((error = git_reference_lookup(&remote_ref, repo, refname)) < 0) goto next; break; next: free(refname); if (error < 0 && error != GIT_ENOTFOUND) break; } if (!remote_ref) { error = GIT_ENOTFOUND; goto out; } if ((error = git_annotated_commit_from_ref(out, repo, remote_ref)) < 0) goto out; out: git_reference_free(remote_ref); git_strarray_dispose(&remotes); return error; } /** That example's entry point */ int lg2_checkout(git_repository *repo, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; checkout_options opts; git_repository_state_t state; git_annotated_commit *checkout_target = NULL; int err = 0; const char *path = "."; /** Parse our command line options */ parse_options(&path, &opts, &args); /** Make sure we're not about to checkout while something else is going on */ state = git_repository_state(repo); if (state != GIT_REPOSITORY_STATE_NONE) { fprintf(stderr, "repository is in unexpected state %d\n", state); goto cleanup; } if (match_arg_separator(&args)) { /** * Try to checkout the given path */ fprintf(stderr, "unhandled path-based checkout\n"); err = 1; goto cleanup; } else { /** * Try to resolve a "refish" argument to a target libgit2 can use */ if ((err = resolve_refish(&checkout_target, repo, args.argv[args.pos])) < 0 && (err = guess_refish(&checkout_target, repo, args.argv[args.pos])) < 0) { fprintf(stderr, "failed to resolve %s: %s\n", args.argv[args.pos], git_error_last()->message); goto cleanup; } err = perform_checkout_ref(repo, checkout_target, args.argv[args.pos], &opts); } cleanup: git_annotated_commit_free(checkout_target); return err; }
libgit2-main
examples/checkout.c
/* * libgit2 "commit" example - shows how to create a git commit * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the libgit2 commit APIs to roughly * simulate `git commit` with the commit message argument. * * This does not have: * * - Robust error handling * - Most of the `git commit` options * * This does have: * * - Example of performing a git commit with a comment * */ int lg2_commit(git_repository *repo, int argc, char **argv) { const char *opt = argv[1]; const char *comment = argv[2]; int error; git_oid commit_oid,tree_oid; git_tree *tree; git_index *index; git_object *parent = NULL; git_reference *ref = NULL; git_signature *signature; /* Validate args */ if (argc < 3 || strcmp(opt, "-m") != 0) { printf ("USAGE: %s -m <comment>\n", argv[0]); return -1; } error = git_revparse_ext(&parent, &ref, repo, "HEAD"); if (error == GIT_ENOTFOUND) { printf("HEAD not found. Creating first commit\n"); error = 0; } else if (error != 0) { const git_error *err = git_error_last(); if (err) printf("ERROR %d: %s\n", err->klass, err->message); else printf("ERROR %d: no detailed info\n", error); } check_lg2(git_repository_index(&index, repo), "Could not open repository index", NULL); check_lg2(git_index_write_tree(&tree_oid, index), "Could not write tree", NULL);; check_lg2(git_index_write(index), "Could not write index", NULL);; check_lg2(git_tree_lookup(&tree, repo, &tree_oid), "Error looking up tree", NULL); check_lg2(git_signature_default(&signature, repo), "Error creating signature", NULL); check_lg2(git_commit_create_v( &commit_oid, repo, "HEAD", signature, signature, NULL, comment, tree, parent ? 1 : 0, parent), "Error creating commit", NULL); git_index_free(index); git_signature_free(signature); git_tree_free(tree); git_object_free(parent); git_reference_free(ref); return error; }
libgit2-main
examples/commit.c
#include "common.h" /* This part is not strictly libgit2-dependent, but you can use this * as a starting point for a git-like tool */ typedef int (*git_command_fn)(git_repository *, int , char **); struct { char *name; git_command_fn fn; char requires_repo; } commands[] = { { "add", lg2_add, 1 }, { "blame", lg2_blame, 1 }, { "cat-file", lg2_cat_file, 1 }, { "checkout", lg2_checkout, 1 }, { "clone", lg2_clone, 0 }, { "commit", lg2_commit, 1 }, { "config", lg2_config, 1 }, { "describe", lg2_describe, 1 }, { "diff", lg2_diff, 1 }, { "fetch", lg2_fetch, 1 }, { "for-each-ref", lg2_for_each_ref, 1 }, { "general", lg2_general, 0 }, { "index-pack", lg2_index_pack, 1 }, { "init", lg2_init, 0 }, { "log", lg2_log, 1 }, { "ls-files", lg2_ls_files, 1 }, { "ls-remote", lg2_ls_remote, 1 }, { "merge", lg2_merge, 1 }, { "push", lg2_push, 1 }, { "remote", lg2_remote, 1 }, { "rev-list", lg2_rev_list, 1 }, { "rev-parse", lg2_rev_parse, 1 }, { "show-index", lg2_show_index, 0 }, { "stash", lg2_stash, 1 }, { "status", lg2_status, 1 }, { "tag", lg2_tag, 1 }, }; static int run_command(git_command_fn fn, git_repository *repo, struct args_info args) { int error; /* Run the command. If something goes wrong, print the error message to stderr */ error = fn(repo, args.argc - args.pos, &args.argv[args.pos]); if (error < 0) { if (git_error_last() == NULL) fprintf(stderr, "Error without message"); else fprintf(stderr, "Bad news:\n %s\n", git_error_last()->message); } return !!error; } static int usage(const char *prog) { size_t i; fprintf(stderr, "usage: %s <cmd>...\n\nAvailable commands:\n\n", prog); for (i = 0; i < ARRAY_SIZE(commands); i++) fprintf(stderr, "\t%s\n", commands[i].name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; git_repository *repo = NULL; const char *git_dir = NULL; int return_code = 1; size_t i; if (argc < 2) usage(argv[0]); git_libgit2_init(); for (args.pos = 1; args.pos < args.argc; ++args.pos) { char *a = args.argv[args.pos]; if (a[0] != '-') { /* non-arg */ break; } else if (optional_str_arg(&git_dir, &args, "--git-dir", ".git")) { continue; } else if (match_arg_separator(&args)) { break; } } if (args.pos == args.argc) usage(argv[0]); if (!git_dir) git_dir = "."; for (i = 0; i < ARRAY_SIZE(commands); ++i) { if (strcmp(args.argv[args.pos], commands[i].name)) continue; /* * Before running the actual command, create an instance * of the local repository and pass it to the function. * */ if (commands[i].requires_repo) { check_lg2(git_repository_open_ext(&repo, git_dir, 0, NULL), "Unable to open repository '%s'", git_dir); } return_code = run_command(commands[i].fn, repo, args); goto shutdown; } fprintf(stderr, "Command not found: %s\n", argv[1]); shutdown: git_repository_free(repo); git_libgit2_shutdown(); return return_code; }
libgit2-main
examples/lg2.c
/* * libgit2 "showindex" example - shows how to extract data from the index * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" int lg2_show_index(git_repository *repo, int argc, char **argv) { git_index *index; size_t i, ecount; char *dir = "."; size_t dirlen; char out[GIT_OID_SHA1_HEXSIZE+1]; out[GIT_OID_SHA1_HEXSIZE] = '\0'; if (argc > 2) fatal("usage: showindex [<repo-dir>]", NULL); if (argc > 1) dir = argv[1]; dirlen = strlen(dir); if (dirlen > 5 && strcmp(dir + dirlen - 5, "index") == 0) { check_lg2(git_index_open(&index, dir), "could not open index", dir); } else { check_lg2(git_repository_open_ext(&repo, dir, 0, NULL), "could not open repository", dir); check_lg2(git_repository_index(&index, repo), "could not open repository index", NULL); git_repository_free(repo); } git_index_read(index, 0); ecount = git_index_entrycount(index); if (!ecount) printf("Empty index\n"); for (i = 0; i < ecount; ++i) { const git_index_entry *e = git_index_get_byindex(index, i); git_oid_fmt(out, &e->id); printf("File Path: %s\n", e->path); printf(" Stage: %d\n", git_index_entry_stage(e)); printf(" Blob SHA: %s\n", out); printf("File Mode: %07o\n", e->mode); printf("File Size: %d bytes\n", (int)e->file_size); printf("Dev/Inode: %d/%d\n", (int)e->dev, (int)e->ino); printf(" UID/GID: %d/%d\n", (int)e->uid, (int)e->gid); printf(" ctime: %d\n", (int)e->ctime.seconds); printf(" mtime: %d\n", (int)e->mtime.seconds); printf("\n"); } git_index_free(index); return 0; }
libgit2-main
examples/show-index.c
/* * libgit2 "blame" example - shows how to use the blame API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates how to invoke the libgit2 blame API to roughly * simulate the output of `git blame` and a few of its command line arguments. */ struct blame_opts { char *path; char *commitspec; int C; int M; int start_line; int end_line; int F; }; static void parse_opts(struct blame_opts *o, int argc, char *argv[]); int lg2_blame(git_repository *repo, int argc, char *argv[]) { int line, break_on_null_hunk; git_object_size_t i, rawsize; char spec[1024] = {0}; struct blame_opts o = {0}; const char *rawdata; git_revspec revspec = {0}; git_blame_options blameopts = GIT_BLAME_OPTIONS_INIT; git_blame *blame = NULL; git_blob *blob; git_object *obj; parse_opts(&o, argc, argv); if (o.M) blameopts.flags |= GIT_BLAME_TRACK_COPIES_SAME_COMMIT_MOVES; if (o.C) blameopts.flags |= GIT_BLAME_TRACK_COPIES_SAME_COMMIT_COPIES; if (o.F) blameopts.flags |= GIT_BLAME_FIRST_PARENT; /** * The commit range comes in "committish" form. Use the rev-parse API to * nail down the end points. */ if (o.commitspec) { check_lg2(git_revparse(&revspec, repo, o.commitspec), "Couldn't parse commit spec", NULL); if (revspec.flags & GIT_REVSPEC_SINGLE) { git_oid_cpy(&blameopts.newest_commit, git_object_id(revspec.from)); git_object_free(revspec.from); } else { git_oid_cpy(&blameopts.oldest_commit, git_object_id(revspec.from)); git_oid_cpy(&blameopts.newest_commit, git_object_id(revspec.to)); git_object_free(revspec.from); git_object_free(revspec.to); } } /** Run the blame. */ check_lg2(git_blame_file(&blame, repo, o.path, &blameopts), "Blame error", NULL); /** * Get the raw data inside the blob for output. We use the * `committish:path/to/file.txt` format to find it. */ if (git_oid_is_zero(&blameopts.newest_commit)) strcpy(spec, "HEAD"); else git_oid_tostr(spec, sizeof(spec), &blameopts.newest_commit); strcat(spec, ":"); strcat(spec, o.path); check_lg2(git_revparse_single(&obj, repo, spec), "Object lookup error", NULL); check_lg2(git_blob_lookup(&blob, repo, git_object_id(obj)), "Blob lookup error", NULL); git_object_free(obj); rawdata = git_blob_rawcontent(blob); rawsize = git_blob_rawsize(blob); /** Produce the output. */ line = 1; i = 0; break_on_null_hunk = 0; while (i < rawsize) { const char *eol = memchr(rawdata + i, '\n', (size_t)(rawsize - i)); char oid[10] = {0}; const git_blame_hunk *hunk = git_blame_get_hunk_byline(blame, line); if (break_on_null_hunk && !hunk) break; if (hunk) { char sig[128] = {0}; break_on_null_hunk = 1; git_oid_tostr(oid, 10, &hunk->final_commit_id); snprintf(sig, 30, "%s <%s>", hunk->final_signature->name, hunk->final_signature->email); printf("%s ( %-30s %3d) %.*s\n", oid, sig, line, (int)(eol - rawdata - i), rawdata + i); } i = (int)(eol - rawdata + 1); line++; } /** Cleanup. */ git_blob_free(blob); git_blame_free(blame); return 0; } /** Tell the user how to make this thing work. */ static void usage(const char *msg, const char *arg) { if (msg && arg) fprintf(stderr, "%s: %s\n", msg, arg); else if (msg) fprintf(stderr, "%s\n", msg); fprintf(stderr, "usage: blame [options] [<commit range>] <path>\n"); fprintf(stderr, "\n"); fprintf(stderr, " <commit range> example: `HEAD~10..HEAD`, or `1234abcd`\n"); fprintf(stderr, " -L <n,m> process only line range n-m, counting from 1\n"); fprintf(stderr, " -M find line moves within and across files\n"); fprintf(stderr, " -C find line copies within and across files\n"); fprintf(stderr, " -F follow only the first parent commits\n"); fprintf(stderr, "\n"); exit(1); } /** Parse the arguments. */ static void parse_opts(struct blame_opts *o, int argc, char *argv[]) { int i; char *bare_args[3] = {0}; if (argc < 2) usage(NULL, NULL); for (i=1; i<argc; i++) { char *a = argv[i]; if (a[0] != '-') { int i=0; while (bare_args[i] && i < 3) ++i; if (i >= 3) usage("Invalid argument set", NULL); bare_args[i] = a; } else if (!strcmp(a, "--")) continue; else if (!strcasecmp(a, "-M")) o->M = 1; else if (!strcasecmp(a, "-C")) o->C = 1; else if (!strcasecmp(a, "-F")) o->F = 1; else if (!strcasecmp(a, "-L")) { i++; a = argv[i]; if (i >= argc) fatal("Not enough arguments to -L", NULL); check_lg2(sscanf(a, "%d,%d", &o->start_line, &o->end_line)-2, "-L format error", NULL); } else { /* commit range */ if (o->commitspec) fatal("Only one commit spec allowed", NULL); o->commitspec = a; } } /* Handle the bare arguments */ if (!bare_args[0]) usage("Please specify a path", NULL); o->path = bare_args[0]; if (bare_args[1]) { /* <commitspec> <path> */ o->path = bare_args[1]; o->commitspec = bare_args[0]; } if (bare_args[2]) { /* <oldcommit> <newcommit> <path> */ char spec[128] = {0}; o->path = bare_args[2]; sprintf(spec, "%s..%s", bare_args[0], bare_args[1]); o->commitspec = spec; } }
libgit2-main
examples/blame.c
/* * libgit2 "config" example - shows how to use the config API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" static int config_get(git_config *cfg, const char *key) { git_config_entry *entry; int error; if ((error = git_config_get_entry(&entry, cfg, key)) < 0) { if (error != GIT_ENOTFOUND) printf("Unable to get configuration: %s\n", git_error_last()->message); return 1; } puts(entry->value); /* Free the git_config_entry after use with `git_config_entry_free()`. */ git_config_entry_free(entry); return 0; } static int config_set(git_config *cfg, const char *key, const char *value) { if (git_config_set_string(cfg, key, value) < 0) { printf("Unable to set configuration: %s\n", git_error_last()->message); return 1; } return 0; } int lg2_config(git_repository *repo, int argc, char **argv) { git_config *cfg; int error; if ((error = git_repository_config(&cfg, repo)) < 0) { printf("Unable to obtain repository config: %s\n", git_error_last()->message); goto out; } if (argc == 2) { error = config_get(cfg, argv[1]); } else if (argc == 3) { error = config_set(cfg, argv[1], argv[2]); } else { printf("USAGE: %s config <KEY> [<VALUE>]\n", argv[0]); error = 1; } /** * The configuration file must be freed once it's no longer * being used by the user. */ git_config_free(cfg); out: return error; }
libgit2-main
examples/config.c
/* * libgit2 "tag" example - shows how to list, create and delete tags * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * The following example partially reimplements the `git tag` command * and some of its options. * * These commands should work: * - Tag name listing (`tag`) * - Filtered tag listing with messages (`tag -n3 -l "v0.1*"`) * - Lightweight tag creation (`tag test v0.18.0`) * - Tag creation (`tag -a -m "Test message" test v0.18.0`) * - Tag deletion (`tag -d test`) * * The command line parsing logic is simplified and doesn't handle * all of the use cases. */ /** tag_options represents the parsed command line options */ struct tag_options { const char *message; const char *pattern; const char *tag_name; const char *target; int num_lines; int force; }; /** tag_state represents the current program state for dragging around */ typedef struct { git_repository *repo; struct tag_options *opts; } tag_state; /** An action to execute based on the command line arguments */ typedef void (*tag_action)(tag_state *state); typedef struct args_info args_info; static void check(int result, const char *message) { if (result) fatal(message, NULL); } /** Tag listing: Print individual message lines */ static void print_list_lines(const char *message, const tag_state *state) { const char *msg = message; int num = state->opts->num_lines - 1; if (!msg) return; /** first line - headline */ while(*msg && *msg != '\n') printf("%c", *msg++); /** skip over new lines */ while(*msg && *msg == '\n') msg++; printf("\n"); /** print just headline? */ if (num == 0) return; if (*msg && msg[1]) printf("\n"); /** print individual commit/tag lines */ while (*msg && num-- >= 2) { printf(" "); while (*msg && *msg != '\n') printf("%c", *msg++); /** handle consecutive new lines */ if (*msg && *msg == '\n' && msg[1] == '\n') { num--; printf("\n"); } while(*msg && *msg == '\n') msg++; printf("\n"); } } /** Tag listing: Print an actual tag object */ static void print_tag(git_tag *tag, const tag_state *state) { printf("%-16s", git_tag_name(tag)); if (state->opts->num_lines) { const char *msg = git_tag_message(tag); print_list_lines(msg, state); } else { printf("\n"); } } /** Tag listing: Print a commit (target of a lightweight tag) */ static void print_commit(git_commit *commit, const char *name, const tag_state *state) { printf("%-16s", name); if (state->opts->num_lines) { const char *msg = git_commit_message(commit); print_list_lines(msg, state); } else { printf("\n"); } } /** Tag listing: Fallback, should not happen */ static void print_name(const char *name) { printf("%s\n", name); } /** Tag listing: Lookup tags based on ref name and dispatch to print */ static int each_tag(const char *name, tag_state *state) { git_repository *repo = state->repo; git_object *obj; check_lg2(git_revparse_single(&obj, repo, name), "Failed to lookup rev", name); switch (git_object_type(obj)) { case GIT_OBJECT_TAG: print_tag((git_tag *) obj, state); break; case GIT_OBJECT_COMMIT: print_commit((git_commit *) obj, name, state); break; default: print_name(name); } git_object_free(obj); return 0; } static void action_list_tags(tag_state *state) { const char *pattern = state->opts->pattern; git_strarray tag_names = {0}; size_t i; check_lg2(git_tag_list_match(&tag_names, pattern ? pattern : "*", state->repo), "Unable to get list of tags", NULL); for(i = 0; i < tag_names.count; i++) { each_tag(tag_names.strings[i], state); } git_strarray_dispose(&tag_names); } static void action_delete_tag(tag_state *state) { struct tag_options *opts = state->opts; git_object *obj; git_buf abbrev_oid = {0}; check(!opts->tag_name, "Name required"); check_lg2(git_revparse_single(&obj, state->repo, opts->tag_name), "Failed to lookup rev", opts->tag_name); check_lg2(git_object_short_id(&abbrev_oid, obj), "Unable to get abbreviated OID", opts->tag_name); check_lg2(git_tag_delete(state->repo, opts->tag_name), "Unable to delete tag", opts->tag_name); printf("Deleted tag '%s' (was %s)\n", opts->tag_name, abbrev_oid.ptr); git_buf_dispose(&abbrev_oid); git_object_free(obj); } static void action_create_lightweight_tag(tag_state *state) { git_repository *repo = state->repo; struct tag_options *opts = state->opts; git_oid oid; git_object *target; check(!opts->tag_name, "Name required"); if (!opts->target) opts->target = "HEAD"; check(!opts->target, "Target required"); check_lg2(git_revparse_single(&target, repo, opts->target), "Unable to resolve spec", opts->target); check_lg2(git_tag_create_lightweight(&oid, repo, opts->tag_name, target, opts->force), "Unable to create tag", NULL); git_object_free(target); } static void action_create_tag(tag_state *state) { git_repository *repo = state->repo; struct tag_options *opts = state->opts; git_signature *tagger; git_oid oid; git_object *target; check(!opts->tag_name, "Name required"); check(!opts->message, "Message required"); if (!opts->target) opts->target = "HEAD"; check_lg2(git_revparse_single(&target, repo, opts->target), "Unable to resolve spec", opts->target); check_lg2(git_signature_default(&tagger, repo), "Unable to create signature", NULL); check_lg2(git_tag_create(&oid, repo, opts->tag_name, target, tagger, opts->message, opts->force), "Unable to create tag", NULL); git_object_free(target); git_signature_free(tagger); } static void print_usage(void) { fprintf(stderr, "usage: see `git help tag`\n"); exit(1); } /** Parse command line arguments and choose action to run when done */ static void parse_options(tag_action *action, struct tag_options *opts, int argc, char **argv) { args_info args = ARGS_INFO_INIT; *action = &action_list_tags; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *curr = argv[args.pos]; if (curr[0] != '-') { if (!opts->tag_name) opts->tag_name = curr; else if (!opts->target) opts->target = curr; else print_usage(); if (*action != &action_create_tag) *action = &action_create_lightweight_tag; } else if (!strcmp(curr, "-n")) { opts->num_lines = 1; *action = &action_list_tags; } else if (!strcmp(curr, "-a")) { *action = &action_create_tag; } else if (!strcmp(curr, "-f")) { opts->force = 1; } else if (match_int_arg(&opts->num_lines, &args, "-n", 0)) { *action = &action_list_tags; } else if (match_str_arg(&opts->pattern, &args, "-l")) { *action = &action_list_tags; } else if (match_str_arg(&opts->tag_name, &args, "-d")) { *action = &action_delete_tag; } else if (match_str_arg(&opts->message, &args, "-m")) { *action = &action_create_tag; } } } /** Initialize tag_options struct */ static void tag_options_init(struct tag_options *opts) { memset(opts, 0, sizeof(*opts)); opts->message = NULL; opts->pattern = NULL; opts->tag_name = NULL; opts->target = NULL; opts->num_lines = 0; opts->force = 0; } int lg2_tag(git_repository *repo, int argc, char **argv) { struct tag_options opts; tag_action action; tag_state state; tag_options_init(&opts); parse_options(&action, &opts, argc, argv); state.repo = repo; state.opts = &opts; action(&state); return 0; }
libgit2-main
examples/tag.c
/* * libgit2 "status" example - shows how to use the status APIs * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * This example demonstrates the use of the libgit2 status APIs, * particularly the `git_status_list` object, to roughly simulate the * output of running `git status`. It serves as a simple example of * using those APIs to get basic status information. * * This does not have: * * - Robust error handling * - Colorized or paginated output formatting * * This does have: * * - Examples of translating command line arguments to the status * options settings to mimic `git status` results. * - A sample status formatter that matches the default "long" format * from `git status` * - A sample status formatter that matches the "short" format */ enum { FORMAT_DEFAULT = 0, FORMAT_LONG = 1, FORMAT_SHORT = 2, FORMAT_PORCELAIN = 3 }; #define MAX_PATHSPEC 8 struct status_opts { git_status_options statusopt; char *repodir; char *pathspec[MAX_PATHSPEC]; int npaths; int format; int zterm; int showbranch; int showsubmod; int repeat; }; static void parse_opts(struct status_opts *o, int argc, char *argv[]); static void show_branch(git_repository *repo, int format); static void print_long(git_status_list *status); static void print_short(git_repository *repo, git_status_list *status); static int print_submod(git_submodule *sm, const char *name, void *payload); int lg2_status(git_repository *repo, int argc, char *argv[]) { git_status_list *status; struct status_opts o = { GIT_STATUS_OPTIONS_INIT, "." }; o.statusopt.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR; o.statusopt.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX | GIT_STATUS_OPT_SORT_CASE_SENSITIVELY; parse_opts(&o, argc, argv); if (git_repository_is_bare(repo)) fatal("Cannot report status on bare repository", git_repository_path(repo)); show_status: if (o.repeat) printf("\033[H\033[2J"); /** * Run status on the repository * * We use `git_status_list_new()` to generate a list of status * information which lets us iterate over it at our * convenience and extract the data we want to show out of * each entry. * * You can use `git_status_foreach()` or * `git_status_foreach_ext()` if you'd prefer to execute a * callback for each entry. The latter gives you more control * about what results are presented. */ check_lg2(git_status_list_new(&status, repo, &o.statusopt), "Could not get status", NULL); if (o.showbranch) show_branch(repo, o.format); if (o.showsubmod) { int submod_count = 0; check_lg2(git_submodule_foreach(repo, print_submod, &submod_count), "Cannot iterate submodules", o.repodir); } if (o.format == FORMAT_LONG) print_long(status); else print_short(repo, status); git_status_list_free(status); if (o.repeat) { sleep(o.repeat); goto show_status; } return 0; } /** * If the user asked for the branch, let's show the short name of the * branch. */ static void show_branch(git_repository *repo, int format) { int error = 0; const char *branch = NULL; git_reference *head = NULL; error = git_repository_head(&head, repo); if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND) branch = NULL; else if (!error) { branch = git_reference_shorthand(head); } else check_lg2(error, "failed to get current branch", NULL); if (format == FORMAT_LONG) printf("# On branch %s\n", branch ? branch : "Not currently on any branch."); else printf("## %s\n", branch ? branch : "HEAD (no branch)"); git_reference_free(head); } /** * This function print out an output similar to git's status command * in long form, including the command-line hints. */ static void print_long(git_status_list *status) { size_t i, maxi = git_status_list_entrycount(status); const git_status_entry *s; int header = 0, changes_in_index = 0; int changed_in_workdir = 0, rm_in_workdir = 0; const char *old_path, *new_path; /** Print index changes. */ for (i = 0; i < maxi; ++i) { char *istatus = NULL; s = git_status_byindex(status, i); if (s->status == GIT_STATUS_CURRENT) continue; if (s->status & GIT_STATUS_WT_DELETED) rm_in_workdir = 1; if (s->status & GIT_STATUS_INDEX_NEW) istatus = "new file: "; if (s->status & GIT_STATUS_INDEX_MODIFIED) istatus = "modified: "; if (s->status & GIT_STATUS_INDEX_DELETED) istatus = "deleted: "; if (s->status & GIT_STATUS_INDEX_RENAMED) istatus = "renamed: "; if (s->status & GIT_STATUS_INDEX_TYPECHANGE) istatus = "typechange:"; if (istatus == NULL) continue; if (!header) { printf("# Changes to be committed:\n"); printf("# (use \"git reset HEAD <file>...\" to unstage)\n"); printf("#\n"); header = 1; } old_path = s->head_to_index->old_file.path; new_path = s->head_to_index->new_file.path; if (old_path && new_path && strcmp(old_path, new_path)) printf("#\t%s %s -> %s\n", istatus, old_path, new_path); else printf("#\t%s %s\n", istatus, old_path ? old_path : new_path); } if (header) { changes_in_index = 1; printf("#\n"); } header = 0; /** Print workdir changes to tracked files. */ for (i = 0; i < maxi; ++i) { char *wstatus = NULL; s = git_status_byindex(status, i); /** * With `GIT_STATUS_OPT_INCLUDE_UNMODIFIED` (not used in this example) * `index_to_workdir` may not be `NULL` even if there are * no differences, in which case it will be a `GIT_DELTA_UNMODIFIED`. */ if (s->status == GIT_STATUS_CURRENT || s->index_to_workdir == NULL) continue; /** Print out the output since we know the file has some changes */ if (s->status & GIT_STATUS_WT_MODIFIED) wstatus = "modified: "; if (s->status & GIT_STATUS_WT_DELETED) wstatus = "deleted: "; if (s->status & GIT_STATUS_WT_RENAMED) wstatus = "renamed: "; if (s->status & GIT_STATUS_WT_TYPECHANGE) wstatus = "typechange:"; if (wstatus == NULL) continue; if (!header) { printf("# Changes not staged for commit:\n"); printf("# (use \"git add%s <file>...\" to update what will be committed)\n", rm_in_workdir ? "/rm" : ""); printf("# (use \"git checkout -- <file>...\" to discard changes in working directory)\n"); printf("#\n"); header = 1; } old_path = s->index_to_workdir->old_file.path; new_path = s->index_to_workdir->new_file.path; if (old_path && new_path && strcmp(old_path, new_path)) printf("#\t%s %s -> %s\n", wstatus, old_path, new_path); else printf("#\t%s %s\n", wstatus, old_path ? old_path : new_path); } if (header) { changed_in_workdir = 1; printf("#\n"); } /** Print untracked files. */ header = 0; for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_WT_NEW) { if (!header) { printf("# Untracked files:\n"); printf("# (use \"git add <file>...\" to include in what will be committed)\n"); printf("#\n"); header = 1; } printf("#\t%s\n", s->index_to_workdir->old_file.path); } } header = 0; /** Print ignored files. */ for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_IGNORED) { if (!header) { printf("# Ignored files:\n"); printf("# (use \"git add -f <file>...\" to include in what will be committed)\n"); printf("#\n"); header = 1; } printf("#\t%s\n", s->index_to_workdir->old_file.path); } } if (!changes_in_index && changed_in_workdir) printf("no changes added to commit (use \"git add\" and/or \"git commit -a\")\n"); } /** * This version of the output prefixes each path with two status * columns and shows submodule status information. */ static void print_short(git_repository *repo, git_status_list *status) { size_t i, maxi = git_status_list_entrycount(status); const git_status_entry *s; char istatus, wstatus; const char *extra, *a, *b, *c; for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_CURRENT) continue; a = b = c = NULL; istatus = wstatus = ' '; extra = ""; if (s->status & GIT_STATUS_INDEX_NEW) istatus = 'A'; if (s->status & GIT_STATUS_INDEX_MODIFIED) istatus = 'M'; if (s->status & GIT_STATUS_INDEX_DELETED) istatus = 'D'; if (s->status & GIT_STATUS_INDEX_RENAMED) istatus = 'R'; if (s->status & GIT_STATUS_INDEX_TYPECHANGE) istatus = 'T'; if (s->status & GIT_STATUS_WT_NEW) { if (istatus == ' ') istatus = '?'; wstatus = '?'; } if (s->status & GIT_STATUS_WT_MODIFIED) wstatus = 'M'; if (s->status & GIT_STATUS_WT_DELETED) wstatus = 'D'; if (s->status & GIT_STATUS_WT_RENAMED) wstatus = 'R'; if (s->status & GIT_STATUS_WT_TYPECHANGE) wstatus = 'T'; if (s->status & GIT_STATUS_IGNORED) { istatus = '!'; wstatus = '!'; } if (istatus == '?' && wstatus == '?') continue; /** * A commit in a tree is how submodules are stored, so * let's go take a look at its status. */ if (s->index_to_workdir && s->index_to_workdir->new_file.mode == GIT_FILEMODE_COMMIT) { unsigned int smstatus = 0; if (!git_submodule_status(&smstatus, repo, s->index_to_workdir->new_file.path, GIT_SUBMODULE_IGNORE_UNSPECIFIED)) { if (smstatus & GIT_SUBMODULE_STATUS_WD_MODIFIED) extra = " (new commits)"; else if (smstatus & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) extra = " (modified content)"; else if (smstatus & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) extra = " (modified content)"; else if (smstatus & GIT_SUBMODULE_STATUS_WD_UNTRACKED) extra = " (untracked content)"; } } /** * Now that we have all the information, format the output. */ if (s->head_to_index) { a = s->head_to_index->old_file.path; b = s->head_to_index->new_file.path; } if (s->index_to_workdir) { if (!a) a = s->index_to_workdir->old_file.path; if (!b) b = s->index_to_workdir->old_file.path; c = s->index_to_workdir->new_file.path; } if (istatus == 'R') { if (wstatus == 'R') printf("%c%c %s %s %s%s\n", istatus, wstatus, a, b, c, extra); else printf("%c%c %s %s%s\n", istatus, wstatus, a, b, extra); } else { if (wstatus == 'R') printf("%c%c %s %s%s\n", istatus, wstatus, a, c, extra); else printf("%c%c %s%s\n", istatus, wstatus, a, extra); } } for (i = 0; i < maxi; ++i) { s = git_status_byindex(status, i); if (s->status == GIT_STATUS_WT_NEW) printf("?? %s\n", s->index_to_workdir->old_file.path); } } static int print_submod(git_submodule *sm, const char *name, void *payload) { int *count = payload; (void)name; if (*count == 0) printf("# Submodules\n"); (*count)++; printf("# - submodule '%s' at %s\n", git_submodule_name(sm), git_submodule_path(sm)); return 0; } /** * Parse options that git's status command supports. */ static void parse_opts(struct status_opts *o, int argc, char *argv[]) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { char *a = argv[args.pos]; if (a[0] != '-') { if (o->npaths < MAX_PATHSPEC) o->pathspec[o->npaths++] = a; else fatal("Example only supports a limited pathspec", NULL); } else if (!strcmp(a, "-s") || !strcmp(a, "--short")) o->format = FORMAT_SHORT; else if (!strcmp(a, "--long")) o->format = FORMAT_LONG; else if (!strcmp(a, "--porcelain")) o->format = FORMAT_PORCELAIN; else if (!strcmp(a, "-b") || !strcmp(a, "--branch")) o->showbranch = 1; else if (!strcmp(a, "-z")) { o->zterm = 1; if (o->format == FORMAT_DEFAULT) o->format = FORMAT_PORCELAIN; } else if (!strcmp(a, "--ignored")) o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED; else if (!strcmp(a, "-uno") || !strcmp(a, "--untracked-files=no")) o->statusopt.flags &= ~GIT_STATUS_OPT_INCLUDE_UNTRACKED; else if (!strcmp(a, "-unormal") || !strcmp(a, "--untracked-files=normal")) o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED; else if (!strcmp(a, "-uall") || !strcmp(a, "--untracked-files=all")) o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS; else if (!strcmp(a, "--ignore-submodules=all")) o->statusopt.flags |= GIT_STATUS_OPT_EXCLUDE_SUBMODULES; else if (!strncmp(a, "--git-dir=", strlen("--git-dir="))) o->repodir = a + strlen("--git-dir="); else if (!strcmp(a, "--repeat")) o->repeat = 10; else if (match_int_arg(&o->repeat, &args, "--repeat", 0)) /* okay */; else if (!strcmp(a, "--list-submodules")) o->showsubmod = 1; else check_lg2(-1, "Unsupported option", a); } if (o->format == FORMAT_DEFAULT) o->format = FORMAT_LONG; if (o->format == FORMAT_LONG) o->showbranch = 1; if (o->npaths > 0) { o->statusopt.pathspec.strings = o->pathspec; o->statusopt.pathspec.count = o->npaths; } }
libgit2-main
examples/status.c
/* * libgit2 "add" example - shows how to modify the index * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * The following example demonstrates how to add files with libgit2. * * It will use the repository in the current working directory, and act * on files passed as its parameters. * * Recognized options are: * -v/--verbose: show the file's status after acting on it. * -n/--dry-run: do not actually change the index. * -u/--update: update the index instead of adding to it. */ enum index_mode { INDEX_NONE, INDEX_ADD }; struct index_options { int dry_run; int verbose; git_repository *repo; enum index_mode mode; int add_update; }; /* Forward declarations for helpers */ static void parse_opts(const char **repo_path, struct index_options *opts, struct args_info *args); int print_matched_cb(const char *path, const char *matched_pathspec, void *payload); int lg2_add(git_repository *repo, int argc, char **argv) { git_index_matched_path_cb matched_cb = NULL; git_index *index; git_strarray array = {0}; struct index_options options = {0}; struct args_info args = ARGS_INFO_INIT; options.mode = INDEX_ADD; /* Parse the options & arguments. */ parse_opts(NULL, &options, &args); strarray_from_args(&array, &args); /* Grab the repository's index. */ check_lg2(git_repository_index(&index, repo), "Could not open repository index", NULL); /* Setup a callback if the requested options need it */ if (options.verbose || options.dry_run) { matched_cb = &print_matched_cb; } options.repo = repo; /* Perform the requested action with the index and files */ if (options.add_update) { git_index_update_all(index, &array, matched_cb, &options); } else { git_index_add_all(index, &array, 0, matched_cb, &options); } /* Cleanup memory */ git_index_write(index); git_index_free(index); return 0; } /* * This callback is called for each file under consideration by * git_index_(update|add)_all above. * It makes uses of the callback's ability to abort the action. */ int print_matched_cb(const char *path, const char *matched_pathspec, void *payload) { struct index_options *opts = (struct index_options *)(payload); int ret; unsigned status; (void)matched_pathspec; /* Get the file status */ if (git_status_file(&status, opts->repo, path) < 0) return -1; if ((status & GIT_STATUS_WT_MODIFIED) || (status & GIT_STATUS_WT_NEW)) { printf("add '%s'\n", path); ret = 0; } else { ret = 1; } if (opts->dry_run) ret = 1; return ret; } static void print_usage(void) { fprintf(stderr, "usage: add [options] [--] file-spec [file-spec] [...]\n\n"); fprintf(stderr, "\t-n, --dry-run dry run\n"); fprintf(stderr, "\t-v, --verbose be verbose\n"); fprintf(stderr, "\t-u, --update update tracked files\n"); exit(1); } static void parse_opts(const char **repo_path, struct index_options *opts, struct args_info *args) { if (args->argc <= 1) print_usage(); for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; if (curr[0] != '-') { if (!strcmp("add", curr)) { opts->mode = INDEX_ADD; continue; } else if (opts->mode == INDEX_NONE) { fprintf(stderr, "missing command: %s", curr); print_usage(); break; } else { /* We might be looking at a filename */ break; } } else if (match_bool_arg(&opts->verbose, args, "--verbose") || match_bool_arg(&opts->dry_run, args, "--dry-run") || match_str_arg(repo_path, args, "--git-dir") || (opts->mode == INDEX_ADD && match_bool_arg(&opts->add_update, args, "--update"))) { continue; } else if (match_bool_arg(NULL, args, "--help")) { print_usage(); break; } else if (match_arg_separator(args)) { break; } else { fprintf(stderr, "Unsupported option %s.\n", curr); print_usage(); } } }
libgit2-main
examples/add.c
#include "common.h" static int use_remote(git_repository *repo, char *name) { git_remote *remote = NULL; int error; const git_remote_head **refs; size_t refs_len, i; git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT; /* Find the remote by name */ error = git_remote_lookup(&remote, repo, name); if (error < 0) { error = git_remote_create_anonymous(&remote, repo, name); if (error < 0) goto cleanup; } /** * Connect to the remote and call the printing function for * each of the remote references. */ callbacks.credentials = cred_acquire_cb; error = git_remote_connect(remote, GIT_DIRECTION_FETCH, &callbacks, NULL, NULL); if (error < 0) goto cleanup; /** * Get the list of references on the remote and print out * their name next to what they point to. */ if (git_remote_ls(&refs, &refs_len, remote) < 0) goto cleanup; for (i = 0; i < refs_len; i++) { char oid[GIT_OID_SHA1_HEXSIZE + 1] = {0}; git_oid_fmt(oid, &refs[i]->oid); printf("%s\t%s\n", oid, refs[i]->name); } cleanup: git_remote_free(remote); return error; } /** Entry point for this command */ int lg2_ls_remote(git_repository *repo, int argc, char **argv) { int error; if (argc < 2) { fprintf(stderr, "usage: %s ls-remote <remote>\n", argv[-1]); return EXIT_FAILURE; } error = use_remote(repo, argv[1]); return error; }
libgit2-main
examples/ls-remote.c
/* * libgit2 "general" example - shows basic libgit2 concepts * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ /** * [**libgit2**][lg] is a portable, pure C implementation of the Git core * methods provided as a re-entrant linkable library with a solid API, * allowing you to write native speed custom Git applications in any * language which supports C bindings. * * This file is an example of using that API in a real, compilable C file. * As the API is updated, this file will be updated to demonstrate the new * functionality. * * If you're trying to write something in C using [libgit2][lg], you should * also check out the generated [API documentation][ap]. We try to link to * the relevant sections of the API docs in each section in this file. * * **libgit2** (for the most part) only implements the core plumbing * functions, not really the higher level porcelain stuff. For a primer on * Git Internals that you will need to know to work with Git at this level, * check out [Chapter 10][pg] of the Pro Git book. * * [lg]: http://libgit2.github.com * [ap]: http://libgit2.github.com/libgit2 * [pg]: https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain */ #include "common.h" /** * ### Includes * * Including the `git2.h` header will include all the other libgit2 headers * that you need. It should be the only thing you need to include in order * to compile properly and get all the libgit2 API. */ #include "git2.h" static void oid_parsing(git_oid *out); static void object_database(git_repository *repo, git_oid *oid); static void commit_writing(git_repository *repo); static void commit_parsing(git_repository *repo); static void tag_parsing(git_repository *repo); static void tree_parsing(git_repository *repo); static void blob_parsing(git_repository *repo); static void revwalking(git_repository *repo); static void index_walking(git_repository *repo); static void reference_listing(git_repository *repo); static void config_files(const char *repo_path, git_repository *repo); /** * Almost all libgit2 functions return 0 on success or negative on error. * This is not production quality error checking, but should be sufficient * as an example. */ static void check_error(int error_code, const char *action) { const git_error *error = git_error_last(); if (!error_code) return; printf("Error %d %s - %s\n", error_code, action, (error && error->message) ? error->message : "???"); exit(1); } int lg2_general(git_repository *repo, int argc, char** argv) { int error; git_oid oid; char *repo_path; /** * Initialize the library, this will set up any global state which libgit2 needs * including threading and crypto */ git_libgit2_init(); /** * ### Opening the Repository * * There are a couple of methods for opening a repository, this being the * simplest. There are also [methods][me] for specifying the index file * and work tree locations, here we assume they are in the normal places. * * (Try running this program against tests/resources/testrepo.git.) * * [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository */ repo_path = (argc > 1) ? argv[1] : "/opt/libgit2-test/.git"; error = git_repository_open(&repo, repo_path); check_error(error, "opening repository"); oid_parsing(&oid); object_database(repo, &oid); commit_writing(repo); commit_parsing(repo); tag_parsing(repo); tree_parsing(repo); blob_parsing(repo); revwalking(repo); index_walking(repo); reference_listing(repo); config_files(repo_path, repo); /** * Finally, when you're done with the repository, you can free it as well. */ git_repository_free(repo); return 0; } /** * ### SHA-1 Value Conversions */ static void oid_parsing(git_oid *oid) { char out[GIT_OID_SHA1_HEXSIZE+1]; char hex[] = "4a202b346bb0fb0db7eff3cffeb3c70babbd2045"; printf("*Hex to Raw*\n"); /** * For our first example, we will convert a 40 character hex value to the * 20 byte raw SHA1 value. * * The `git_oid` is the structure that keeps the SHA value. We will use * this throughout the example for storing the value of the current SHA * key we're working with. */ #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(oid, hex, GIT_OID_SHA1); #else git_oid_fromstr(oid, hex); #endif /* * Once we've converted the string into the oid value, we can get the raw * value of the SHA by accessing `oid.id` * * Next we will convert the 20 byte raw SHA1 value to a human readable 40 * char hex value. */ printf("\n*Raw to Hex*\n"); out[GIT_OID_SHA1_HEXSIZE] = '\0'; /** * If you have a oid, you can easily get the hex value of the SHA as well. */ git_oid_fmt(out, oid); printf("SHA hex string: %s\n", out); } /** * ### Working with the Object Database * * **libgit2** provides [direct access][odb] to the object database. The * object database is where the actual objects are stored in Git. For * working with raw objects, we'll need to get this structure from the * repository. * * [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb */ static void object_database(git_repository *repo, git_oid *oid) { char oid_hex[GIT_OID_SHA1_HEXSIZE+1] = { 0 }; const unsigned char *data; const char *str_type; int error; git_odb_object *obj; git_odb *odb; git_object_t otype; git_repository_odb(&odb, repo); /** * #### Raw Object Reading */ printf("\n*Raw Object Read*\n"); /** * We can read raw objects directly from the object database if we have * the oid (SHA) of the object. This allows us to access objects without * knowing their type and inspect the raw bytes unparsed. */ error = git_odb_read(&obj, odb, oid); check_error(error, "finding object in repository"); /** * A raw object only has three properties - the type (commit, blob, tree * or tag), the size of the raw data and the raw, unparsed data itself. * For a commit or tag, that raw data is human readable plain ASCII * text. For a blob it is just file contents, so it could be text or * binary data. For a tree it is a special binary format, so it's unlikely * to be hugely helpful as a raw object. */ data = (const unsigned char *)git_odb_object_data(obj); otype = git_odb_object_type(obj); /** * We provide methods to convert from the object type which is an enum, to * a string representation of that value (and vice-versa). */ str_type = git_object_type2string(otype); printf("object length and type: %d, %s\nobject data: %s\n", (int)git_odb_object_size(obj), str_type, data); /** * For proper memory management, close the object when you are done with * it or it will leak memory. */ git_odb_object_free(obj); /** * #### Raw Object Writing */ printf("\n*Raw Object Write*\n"); /** * You can also write raw object data to Git. This is pretty cool because * it gives you direct access to the key/value properties of Git. Here * we'll write a new blob object that just contains a simple string. * Notice that we have to specify the object type as the `git_otype` enum. */ git_odb_write(oid, odb, "test data", sizeof("test data") - 1, GIT_OBJECT_BLOB); /** * Now that we've written the object, we can check out what SHA1 was * generated when the object was written to our database. */ git_oid_fmt(oid_hex, oid); printf("Written Object: %s\n", oid_hex); /** * Free the object database after usage. */ git_odb_free(odb); } /** * #### Writing Commits * * libgit2 provides a couple of methods to create commit objects easily as * well. There are four different create signatures, we'll just show one * of them here. You can read about the other ones in the [commit API * docs][cd]. * * [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit */ static void commit_writing(git_repository *repo) { git_oid tree_id, parent_id, commit_id; git_tree *tree; git_commit *parent; git_signature *author, *committer; char oid_hex[GIT_OID_SHA1_HEXSIZE+1] = { 0 }; printf("\n*Commit Writing*\n"); /** * Creating signatures for an authoring identity and time is simple. You * will need to do this to specify who created a commit and when. Default * values for the name and email should be found in the `user.name` and * `user.email` configuration options. See the `config` section of this * example file to see how to access config values. */ git_signature_new(&author, "Scott Chacon", "[email protected]", 123456789, 60); git_signature_new(&committer, "Scott A Chacon", "[email protected]", 987654321, 90); /** * Commit objects need a tree to point to and optionally one or more * parents. Here we're creating oid objects to create the commit with, * but you can also use */ #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(&tree_id, "f60079018b664e4e79329a7ef9559c8d9e0378d1", GIT_OID_SHA1); git_oid_fromstr(&parent_id, "5b5b025afb0b4c913b4c338a42934a3863bf3644", GIT_OID_SHA1); #else git_oid_fromstr(&tree_id, "f60079018b664e4e79329a7ef9559c8d9e0378d1"); git_oid_fromstr(&parent_id, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); #endif git_tree_lookup(&tree, repo, &tree_id); git_commit_lookup(&parent, repo, &parent_id); /** * Here we actually create the commit object with a single call with all * the values we need to create the commit. The SHA key is written to the * `commit_id` variable here. */ git_commit_create_v( &commit_id, /* out id */ repo, NULL, /* do not update the HEAD */ author, committer, NULL, /* use default message encoding */ "example commit", tree, 1, parent); /** * Now we can take a look at the commit SHA we've generated. */ git_oid_fmt(oid_hex, &commit_id); printf("New Commit: %s\n", oid_hex); /** * Free all objects used in the meanwhile. */ git_tree_free(tree); git_commit_free(parent); git_signature_free(author); git_signature_free(committer); } /** * ### Object Parsing * * libgit2 has methods to parse every object type in Git so you don't have * to work directly with the raw data. This is much faster and simpler * than trying to deal with the raw data yourself. */ /** * #### Commit Parsing * * [Parsing commit objects][pco] is simple and gives you access to all the * data in the commit - the author (name, email, datetime), committer * (same), tree, message, encoding and parent(s). * * [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit */ static void commit_parsing(git_repository *repo) { const git_signature *author, *cmtter; git_commit *commit, *parent; git_oid oid; char oid_hex[GIT_OID_SHA1_HEXSIZE+1]; const char *message; unsigned int parents, p; int error; time_t time; printf("\n*Commit Parsing*\n"); #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(&oid, "8496071c1b46c854b31185ea97743be6a8774479", GIT_OID_SHA1); #else git_oid_fromstr(&oid, "8496071c1b46c854b31185ea97743be6a8774479"); #endif error = git_commit_lookup(&commit, repo, &oid); check_error(error, "looking up commit"); /** * Each of the properties of the commit object are accessible via methods, * including commonly needed variations, such as `git_commit_time` which * returns the author time and `git_commit_message` which gives you the * commit message (as a NUL-terminated string). */ message = git_commit_message(commit); author = git_commit_author(commit); cmtter = git_commit_committer(commit); time = git_commit_time(commit); /** * The author and committer methods return [git_signature] structures, * which give you name, email and `when`, which is a `git_time` structure, * giving you a timestamp and timezone offset. */ printf("Author: %s (%s)\nCommitter: %s (%s)\nDate: %s\nMessage: %s\n", author->name, author->email, cmtter->name, cmtter->email, ctime(&time), message); /** * Commits can have zero or more parents. The first (root) commit will * have no parents, most commits will have one (i.e. the commit it was * based on) and merge commits will have two or more. Commits can * technically have any number, though it's rare to have more than two. */ parents = git_commit_parentcount(commit); for (p = 0;p < parents;p++) { memset(oid_hex, 0, sizeof(oid_hex)); git_commit_parent(&parent, commit, p); git_oid_fmt(oid_hex, git_commit_id(parent)); printf("Parent: %s\n", oid_hex); git_commit_free(parent); } git_commit_free(commit); } /** * #### Tag Parsing * * You can parse and create tags with the [tag management API][tm], which * functions very similarly to the commit lookup, parsing and creation * methods, since the objects themselves are very similar. * * [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag */ static void tag_parsing(git_repository *repo) { git_commit *commit; git_object_t type; git_tag *tag; git_oid oid; const char *name, *message; int error; printf("\n*Tag Parsing*\n"); /** * We create an oid for the tag object if we know the SHA and look it up * the same way that we would a commit (or any other object). */ #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(&oid, "b25fa35b38051e4ae45d4222e795f9df2e43f1d1", GIT_OID_SHA1); #else git_oid_fromstr(&oid, "b25fa35b38051e4ae45d4222e795f9df2e43f1d1"); #endif error = git_tag_lookup(&tag, repo, &oid); check_error(error, "looking up tag"); /** * Now that we have the tag object, we can extract the information it * generally contains: the target (usually a commit object), the type of * the target object (usually 'commit'), the name ('v1.0'), the tagger (a * git_signature - name, email, timestamp), and the tag message. */ git_tag_target((git_object **)&commit, tag); name = git_tag_name(tag); /* "test" */ type = git_tag_target_type(tag); /* GIT_OBJECT_COMMIT (object_t enum) */ message = git_tag_message(tag); /* "tag message\n" */ printf("Tag Name: %s\nTag Type: %s\nTag Message: %s\n", name, git_object_type2string(type), message); /** * Free both the commit and tag after usage. */ git_commit_free(commit); git_tag_free(tag); } /** * #### Tree Parsing * * [Tree parsing][tp] is a bit different than the other objects, in that * we have a subtype which is the tree entry. This is not an actual * object type in Git, but a useful structure for parsing and traversing * tree entries. * * [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree */ static void tree_parsing(git_repository *repo) { const git_tree_entry *entry; size_t cnt; git_object *obj; git_tree *tree; git_oid oid; printf("\n*Tree Parsing*\n"); /** * Create the oid and lookup the tree object just like the other objects. */ #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(&oid, "f60079018b664e4e79329a7ef9559c8d9e0378d1", GIT_OID_SHA1); #else git_oid_fromstr(&oid, "f60079018b664e4e79329a7ef9559c8d9e0378d1"); #endif git_tree_lookup(&tree, repo, &oid); /** * Getting the count of entries in the tree so you can iterate over them * if you want to. */ cnt = git_tree_entrycount(tree); /* 2 */ printf("tree entries: %d\n", (int) cnt); entry = git_tree_entry_byindex(tree, 0); printf("Entry name: %s\n", git_tree_entry_name(entry)); /* "README" */ /** * You can also access tree entries by name if you know the name of the * entry you're looking for. */ entry = git_tree_entry_byname(tree, "README"); git_tree_entry_name(entry); /* "README" */ /** * Once you have the entry object, you can access the content or subtree * (or commit, in the case of submodules) that it points to. You can also * get the mode if you want. */ git_tree_entry_to_object(&obj, repo, entry); /* blob */ /** * Remember to close the looked-up object and tree once you are done using it */ git_object_free(obj); git_tree_free(tree); } /** * #### Blob Parsing * * The last object type is the simplest and requires the least parsing * help. Blobs are just file contents and can contain anything, there is * no structure to it. The main advantage to using the [simple blob * api][ba] is that when you're creating blobs you don't have to calculate * the size of the content. There is also a helper for reading a file * from disk and writing it to the db and getting the oid back so you * don't have to do all those steps yourself. * * [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob */ static void blob_parsing(git_repository *repo) { git_blob *blob; git_oid oid; printf("\n*Blob Parsing*\n"); #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(&oid, "1385f264afb75a56a5bec74243be9b367ba4ca08", GIT_OID_SHA1); #else git_oid_fromstr(&oid, "1385f264afb75a56a5bec74243be9b367ba4ca08"); #endif git_blob_lookup(&blob, repo, &oid); /** * You can access a buffer with the raw contents of the blob directly. * Note that this buffer may not be contain ASCII data for certain blobs * (e.g. binary files): do not consider the buffer a NULL-terminated * string, and use the `git_blob_rawsize` attribute to find out its exact * size in bytes * */ printf("Blob Size: %ld\n", (long)git_blob_rawsize(blob)); /* 8 */ git_blob_rawcontent(blob); /* "content" */ /** * Free the blob after usage. */ git_blob_free(blob); } /** * ### Revwalking * * The libgit2 [revision walking api][rw] provides methods to traverse the * directed graph created by the parent pointers of the commit objects. * Since all commits point back to the commit that came directly before * them, you can walk this parentage as a graph and find all the commits * that were ancestors of (reachable from) a given starting point. This * can allow you to create `git log` type functionality. * * [rw]: http://libgit2.github.com/libgit2/#HEAD/group/revwalk */ static void revwalking(git_repository *repo) { const git_signature *cauth; const char *cmsg; int error; git_revwalk *walk; git_commit *wcommit; git_oid oid; printf("\n*Revwalking*\n"); #ifdef GIT_EXPERIMENTAL_SHA256 git_oid_fromstr(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644", GIT_OID_SHA1); #else git_oid_fromstr(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); #endif /** * To use the revwalker, create a new walker, tell it how you want to sort * the output and then push one or more starting points onto the walker. * If you want to emulate the output of `git log` you would push the SHA * of the commit that HEAD points to into the walker and then start * traversing them. You can also 'hide' commits that you want to stop at * or not see any of their ancestors. So if you want to emulate `git log * branch1..branch2`, you would push the oid of `branch2` and hide the oid * of `branch1`. */ git_revwalk_new(&walk, repo); git_revwalk_sorting(walk, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE); git_revwalk_push(walk, &oid); /** * Now that we have the starting point pushed onto the walker, we start * asking for ancestors. It will return them in the sorting order we asked * for as commit oids. We can then lookup and parse the committed pointed * at by the returned OID; note that this operation is specially fast * since the raw contents of the commit object will be cached in memory */ while ((git_revwalk_next(&oid, walk)) == 0) { error = git_commit_lookup(&wcommit, repo, &oid); check_error(error, "looking up commit during revwalk"); cmsg = git_commit_message(wcommit); cauth = git_commit_author(wcommit); printf("%s (%s)\n", cmsg, cauth->email); git_commit_free(wcommit); } /** * Like the other objects, be sure to free the revwalker when you're done * to prevent memory leaks. Also, make sure that the repository being * walked it not deallocated while the walk is in progress, or it will * result in undefined behavior */ git_revwalk_free(walk); } /** * ### Index File Manipulation * * The [index file API][gi] allows you to read, traverse, update and write * the Git index file (sometimes thought of as the staging area). * * [gi]: http://libgit2.github.com/libgit2/#HEAD/group/index */ static void index_walking(git_repository *repo) { git_index *index; size_t i, ecount; printf("\n*Index Walking*\n"); /** * You can either open the index from the standard location in an open * repository, as we're doing here, or you can open and manipulate any * index file with `git_index_open_bare()`. The index for the repository * will be located and loaded from disk. */ git_repository_index(&index, repo); /** * For each entry in the index, you can get a bunch of information * including the SHA (oid), path and mode which map to the tree objects * that are written out. It also has filesystem properties to help * determine what to inspect for changes (ctime, mtime, dev, ino, uid, * gid, file_size and flags) All these properties are exported publicly in * the `git_index_entry` struct */ ecount = git_index_entrycount(index); for (i = 0; i < ecount; ++i) { const git_index_entry *e = git_index_get_byindex(index, i); printf("path: %s\n", e->path); printf("mtime: %d\n", (int)e->mtime.seconds); printf("fs: %d\n", (int)e->file_size); } git_index_free(index); } /** * ### References * * The [reference API][ref] allows you to list, resolve, create and update * references such as branches, tags and remote references (everything in * the .git/refs directory). * * [ref]: http://libgit2.github.com/libgit2/#HEAD/group/reference */ static void reference_listing(git_repository *repo) { git_strarray ref_list; unsigned i; printf("\n*Reference Listing*\n"); /** * Here we will implement something like `git for-each-ref` simply listing * out all available references and the object SHA they resolve to. * * Now that we have the list of reference names, we can lookup each ref * one at a time and resolve them to the SHA, then print both values out. */ git_reference_list(&ref_list, repo); for (i = 0; i < ref_list.count; ++i) { git_reference *ref; char oid_hex[GIT_OID_SHA1_HEXSIZE+1] = GIT_OID_SHA1_HEXZERO; const char *refname; refname = ref_list.strings[i]; git_reference_lookup(&ref, repo, refname); switch (git_reference_type(ref)) { case GIT_REFERENCE_DIRECT: git_oid_fmt(oid_hex, git_reference_target(ref)); printf("%s [%s]\n", refname, oid_hex); break; case GIT_REFERENCE_SYMBOLIC: printf("%s => %s\n", refname, git_reference_symbolic_target(ref)); break; default: fprintf(stderr, "Unexpected reference type\n"); exit(1); } git_reference_free(ref); } git_strarray_dispose(&ref_list); } /** * ### Config Files * * The [config API][config] allows you to list and update config values * in any of the accessible config file locations (system, global, local). * * [config]: http://libgit2.github.com/libgit2/#HEAD/group/config */ static void config_files(const char *repo_path, git_repository* repo) { const char *email; char config_path[256]; int32_t autocorrect; git_config *cfg; git_config *snap_cfg; int error_code; printf("\n*Config Listing*\n"); /** * Open a config object so we can read global values from it. */ sprintf(config_path, "%s/config", repo_path); check_error(git_config_open_ondisk(&cfg, config_path), "opening config"); if (git_config_get_int32(&autocorrect, cfg, "help.autocorrect") == 0) printf("Autocorrect: %d\n", autocorrect); check_error(git_repository_config_snapshot(&snap_cfg, repo), "config snapshot"); git_config_get_string(&email, snap_cfg, "user.email"); printf("Email: %s\n", email); error_code = git_config_get_int32(&autocorrect, cfg, "help.autocorrect"); switch (error_code) { case 0: printf("Autocorrect: %d\n", autocorrect); break; case GIT_ENOTFOUND: printf("Autocorrect: Undefined\n"); break; default: check_error(error_code, "get_int32 failed"); } git_config_free(cfg); check_error(git_repository_config_snapshot(&snap_cfg, repo), "config snapshot"); error_code = git_config_get_string(&email, snap_cfg, "user.email"); switch (error_code) { case 0: printf("Email: %s\n", email); break; case GIT_ENOTFOUND: printf("Email: Undefined\n"); break; default: check_error(error_code, "get_string failed"); } git_config_free(snap_cfg); }
libgit2-main
examples/general.c
#include "common.h" typedef struct progress_data { git_indexer_progress fetch_progress; size_t completed_steps; size_t total_steps; const char *path; } progress_data; static void print_progress(const progress_data *pd) { int network_percent = pd->fetch_progress.total_objects > 0 ? (100*pd->fetch_progress.received_objects) / pd->fetch_progress.total_objects : 0; int index_percent = pd->fetch_progress.total_objects > 0 ? (100*pd->fetch_progress.indexed_objects) / pd->fetch_progress.total_objects : 0; int checkout_percent = pd->total_steps > 0 ? (int)((100 * pd->completed_steps) / pd->total_steps) : 0; size_t kbytes = pd->fetch_progress.received_bytes / 1024; if (pd->fetch_progress.total_objects && pd->fetch_progress.received_objects == pd->fetch_progress.total_objects) { printf("Resolving deltas %u/%u\r", pd->fetch_progress.indexed_deltas, pd->fetch_progress.total_deltas); } else { printf("net %3d%% (%4" PRIuZ " kb, %5u/%5u) / idx %3d%% (%5u/%5u) / chk %3d%% (%4" PRIuZ "/%4" PRIuZ")%s\n", network_percent, kbytes, pd->fetch_progress.received_objects, pd->fetch_progress.total_objects, index_percent, pd->fetch_progress.indexed_objects, pd->fetch_progress.total_objects, checkout_percent, pd->completed_steps, pd->total_steps, pd->path); } } static int sideband_progress(const char *str, int len, void *payload) { (void)payload; /* unused */ printf("remote: %.*s", len, str); fflush(stdout); return 0; } static int fetch_progress(const git_indexer_progress *stats, void *payload) { progress_data *pd = (progress_data*)payload; pd->fetch_progress = *stats; print_progress(pd); return 0; } static void checkout_progress(const char *path, size_t cur, size_t tot, void *payload) { progress_data *pd = (progress_data*)payload; pd->completed_steps = cur; pd->total_steps = tot; pd->path = path; print_progress(pd); } int lg2_clone(git_repository *repo, int argc, char **argv) { progress_data pd = {{0}}; git_repository *cloned_repo = NULL; git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; const char *url = argv[1]; const char *path = argv[2]; int error; (void)repo; /* unused */ /* Validate args */ if (argc < 3) { printf ("USAGE: %s <url> <path>\n", argv[0]); return -1; } /* Set up options */ checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; checkout_opts.progress_cb = checkout_progress; checkout_opts.progress_payload = &pd; clone_opts.checkout_opts = checkout_opts; clone_opts.fetch_opts.callbacks.sideband_progress = sideband_progress; clone_opts.fetch_opts.callbacks.transfer_progress = &fetch_progress; clone_opts.fetch_opts.callbacks.credentials = cred_acquire_cb; clone_opts.fetch_opts.callbacks.payload = &pd; /* Do the clone */ error = git_clone(&cloned_repo, url, path, &clone_opts); printf("\n"); if (error != 0) { const git_error *err = git_error_last(); if (err) printf("ERROR %d: %s\n", err->klass, err->message); else printf("ERROR %d: no detailed info\n", error); } else if (cloned_repo) git_repository_free(cloned_repo); return error; }
libgit2-main
examples/clone.c
/* * libgit2 "stash" example - shows how to use the stash API * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <stdarg.h> #include "common.h" enum subcmd { SUBCMD_APPLY, SUBCMD_LIST, SUBCMD_POP, SUBCMD_PUSH }; struct opts { enum subcmd cmd; int argc; char **argv; }; static void usage(const char *fmt, ...) { va_list ap; fputs("usage: git stash list\n", stderr); fputs(" or: git stash ( pop | apply )\n", stderr); fputs(" or: git stash [push]\n", stderr); fputs("\n", stderr); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); exit(1); } static void parse_subcommand(struct opts *opts, int argc, char *argv[]) { char *arg = (argc < 2) ? "push" : argv[1]; enum subcmd cmd; if (!strcmp(arg, "apply")) { cmd = SUBCMD_APPLY; } else if (!strcmp(arg, "list")) { cmd = SUBCMD_LIST; } else if (!strcmp(arg, "pop")) { cmd = SUBCMD_POP; } else if (!strcmp(arg, "push")) { cmd = SUBCMD_PUSH; } else { usage("invalid command %s", arg); return; } opts->cmd = cmd; opts->argc = (argc < 2) ? argc - 1 : argc - 2; opts->argv = argv; } static int cmd_apply(git_repository *repo, struct opts *opts) { if (opts->argc) usage("apply does not accept any parameters"); check_lg2(git_stash_apply(repo, 0, NULL), "Unable to apply stash", NULL); return 0; } static int list_stash_cb(size_t index, const char *message, const git_oid *stash_id, void *payload) { UNUSED(stash_id); UNUSED(payload); printf("stash@{%"PRIuZ"}: %s\n", index, message); return 0; } static int cmd_list(git_repository *repo, struct opts *opts) { if (opts->argc) usage("list does not accept any parameters"); check_lg2(git_stash_foreach(repo, list_stash_cb, NULL), "Unable to list stashes", NULL); return 0; } static int cmd_push(git_repository *repo, struct opts *opts) { git_signature *signature; git_commit *stash; git_oid stashid; if (opts->argc) usage("push does not accept any parameters"); check_lg2(git_signature_default(&signature, repo), "Unable to get signature", NULL); check_lg2(git_stash_save(&stashid, repo, signature, NULL, GIT_STASH_DEFAULT), "Unable to save stash", NULL); check_lg2(git_commit_lookup(&stash, repo, &stashid), "Unable to lookup stash commit", NULL); printf("Saved working directory %s\n", git_commit_summary(stash)); git_signature_free(signature); git_commit_free(stash); return 0; } static int cmd_pop(git_repository *repo, struct opts *opts) { if (opts->argc) usage("pop does not accept any parameters"); check_lg2(git_stash_pop(repo, 0, NULL), "Unable to pop stash", NULL); printf("Dropped refs/stash@{0}\n"); return 0; } int lg2_stash(git_repository *repo, int argc, char *argv[]) { struct opts opts = { 0 }; parse_subcommand(&opts, argc, argv); switch (opts.cmd) { case SUBCMD_APPLY: return cmd_apply(repo, &opts); case SUBCMD_LIST: return cmd_list(repo, &opts); case SUBCMD_PUSH: return cmd_push(repo, &opts); case SUBCMD_POP: return cmd_pop(repo, &opts); } return -1; }
libgit2-main
examples/stash.c
/* * libgit2 "describe" example - shows how to describe commits * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** * The following example partially reimplements the `git describe` command * and some of its options. * * These commands should work: * - Describe HEAD with default options (`describe`) * - Describe specified revision (`describe master~2`) * - Describe specified revisions (`describe master~2 HEAD~3`) * - Describe HEAD with dirty state suffix (`describe --dirty=*`) * - Describe consider all refs (`describe --all master`) * - Describe consider lightweight tags (`describe --tags temp-tag`) * - Describe show non-default abbreviated size (`describe --abbrev=10`) * - Describe always output the long format if matches a tag (`describe --long v1.0`) * - Describe consider only tags of specified pattern (`describe --match v*-release`) * - Describe show the fallback result (`describe --always`) * - Describe follow only the first parent commit (`describe --first-parent`) * * The command line parsing logic is simplified and doesn't handle * all of the use cases. */ /** describe_options represents the parsed command line options */ struct describe_options { const char **commits; size_t commit_count; git_describe_options describe_options; git_describe_format_options format_options; }; static void opts_add_commit(struct describe_options *opts, const char *commit) { size_t sz; assert(opts != NULL); sz = ++opts->commit_count * sizeof(opts->commits[0]); opts->commits = xrealloc((void *) opts->commits, sz); opts->commits[opts->commit_count - 1] = commit; } static void do_describe_single(git_repository *repo, struct describe_options *opts, const char *rev) { git_object *commit; git_describe_result *describe_result; git_buf buf = { 0 }; if (rev) { check_lg2(git_revparse_single(&commit, repo, rev), "Failed to lookup rev", rev); check_lg2(git_describe_commit(&describe_result, commit, &opts->describe_options), "Failed to describe rev", rev); } else check_lg2(git_describe_workdir(&describe_result, repo, &opts->describe_options), "Failed to describe workdir", NULL); check_lg2(git_describe_format(&buf, describe_result, &opts->format_options), "Failed to format describe rev", rev); printf("%s\n", buf.ptr); } static void do_describe(git_repository *repo, struct describe_options *opts) { if (opts->commit_count == 0) do_describe_single(repo, opts, NULL); else { size_t i; for (i = 0; i < opts->commit_count; i++) do_describe_single(repo, opts, opts->commits[i]); } } static void print_usage(void) { fprintf(stderr, "usage: see `git help describe`\n"); exit(1); } /** Parse command line arguments */ static void parse_options(struct describe_options *opts, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; for (args.pos = 1; args.pos < argc; ++args.pos) { const char *curr = argv[args.pos]; if (curr[0] != '-') { opts_add_commit(opts, curr); } else if (!strcmp(curr, "--all")) { opts->describe_options.describe_strategy = GIT_DESCRIBE_ALL; } else if (!strcmp(curr, "--tags")) { opts->describe_options.describe_strategy = GIT_DESCRIBE_TAGS; } else if (!strcmp(curr, "--exact-match")) { opts->describe_options.max_candidates_tags = 0; } else if (!strcmp(curr, "--long")) { opts->format_options.always_use_long_format = 1; } else if (!strcmp(curr, "--always")) { opts->describe_options.show_commit_oid_as_fallback = 1; } else if (!strcmp(curr, "--first-parent")) { opts->describe_options.only_follow_first_parent = 1; } else if (optional_str_arg(&opts->format_options.dirty_suffix, &args, "--dirty", "-dirty")) { } else if (match_int_arg((int *)&opts->format_options.abbreviated_size, &args, "--abbrev", 0)) { } else if (match_int_arg((int *)&opts->describe_options.max_candidates_tags, &args, "--candidates", 0)) { } else if (match_str_arg(&opts->describe_options.pattern, &args, "--match")) { } else { print_usage(); } } if (opts->commit_count > 0) { if (opts->format_options.dirty_suffix) fatal("--dirty is incompatible with commit-ishes", NULL); } else { if (!opts->format_options.dirty_suffix || !opts->format_options.dirty_suffix[0]) { opts_add_commit(opts, "HEAD"); } } } /** Initialize describe_options struct */ static void describe_options_init(struct describe_options *opts) { memset(opts, 0, sizeof(*opts)); opts->commits = NULL; opts->commit_count = 0; git_describe_options_init(&opts->describe_options, GIT_DESCRIBE_OPTIONS_VERSION); git_describe_format_options_init(&opts->format_options, GIT_DESCRIBE_FORMAT_OPTIONS_VERSION); } int lg2_describe(git_repository *repo, int argc, char **argv) { struct describe_options opts; describe_options_init(&opts); parse_options(&opts, argc, argv); do_describe(repo, &opts); return 0; }
libgit2-main
examples/describe.c
/* * libgit2 "rev-list" example - shows how to transform a rev-spec into a list * of commit ids * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" #include <assert.h> static int revwalk_parse_options(git_sort_t *sort, struct args_info *args); static int revwalk_parse_revs(git_repository *repo, git_revwalk *walk, struct args_info *args); int lg2_rev_list(git_repository *repo, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; git_revwalk *walk; git_oid oid; git_sort_t sort; char buf[GIT_OID_SHA1_HEXSIZE+1]; check_lg2(revwalk_parse_options(&sort, &args), "parsing options", NULL); check_lg2(git_revwalk_new(&walk, repo), "allocating revwalk", NULL); git_revwalk_sorting(walk, sort); check_lg2(revwalk_parse_revs(repo, walk, &args), "parsing revs", NULL); while (!git_revwalk_next(&oid, walk)) { git_oid_fmt(buf, &oid); buf[GIT_OID_SHA1_HEXSIZE] = '\0'; printf("%s\n", buf); } git_revwalk_free(walk); return 0; } static int push_commit(git_revwalk *walk, const git_oid *oid, int hide) { if (hide) return git_revwalk_hide(walk, oid); else return git_revwalk_push(walk, oid); } static int push_spec(git_repository *repo, git_revwalk *walk, const char *spec, int hide) { int error; git_object *obj; if ((error = git_revparse_single(&obj, repo, spec)) < 0) return error; error = push_commit(walk, git_object_id(obj), hide); git_object_free(obj); return error; } static int push_range(git_repository *repo, git_revwalk *walk, const char *range, int hide) { git_revspec revspec; int error = 0; if ((error = git_revparse(&revspec, repo, range))) return error; if (revspec.flags & GIT_REVSPEC_MERGE_BASE) { /* TODO: support "<commit>...<commit>" */ return GIT_EINVALIDSPEC; } if ((error = push_commit(walk, git_object_id(revspec.from), !hide))) goto out; error = push_commit(walk, git_object_id(revspec.to), hide); out: git_object_free(revspec.from); git_object_free(revspec.to); return error; } static void print_usage(void) { fprintf(stderr, "rev-list [--git-dir=dir] [--topo-order|--date-order] [--reverse] <revspec>\n"); exit(-1); } static int revwalk_parse_options(git_sort_t *sort, struct args_info *args) { assert(sort && args); *sort = GIT_SORT_NONE; if (args->argc < 1) print_usage(); for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; if (!strcmp(curr, "--topo-order")) { *sort |= GIT_SORT_TOPOLOGICAL; } else if (!strcmp(curr, "--date-order")) { *sort |= GIT_SORT_TIME; } else if (!strcmp(curr, "--reverse")) { *sort |= (*sort & ~GIT_SORT_REVERSE) ^ GIT_SORT_REVERSE; } else { break; } } return 0; } static int revwalk_parse_revs(git_repository *repo, git_revwalk *walk, struct args_info *args) { int hide, error; git_oid oid; hide = 0; for (; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; if (!strcmp(curr, "--not")) { hide = !hide; } else if (curr[0] == '^') { if ((error = push_spec(repo, walk, curr + 1, !hide))) return error; } else if (strstr(curr, "..")) { if ((error = push_range(repo, walk, curr, hide))) return error; } else { if (push_spec(repo, walk, curr, hide) == 0) continue; #ifdef GIT_EXPERIMENTAL_SHA256 if ((error = git_oid_fromstr(&oid, curr, GIT_OID_SHA1))) return error; #else if ((error = git_oid_fromstr(&oid, curr))) return error; #endif if ((error = push_commit(walk, &oid, hide))) return error; } } return 0; }
libgit2-main
examples/rev-list.c
#include "common.h" /* * This could be run in the main loop whilst the application waits for * the indexing to finish in a worker thread */ static int index_cb(const git_indexer_progress *stats, void *data) { (void)data; printf("\rProcessing %u of %u", stats->indexed_objects, stats->total_objects); return 0; } int lg2_index_pack(git_repository *repo, int argc, char **argv) { git_indexer *idx; git_indexer_progress stats = {0, 0}; int error; int fd; ssize_t read_bytes; char buf[512]; (void)repo; if (argc < 2) { fprintf(stderr, "usage: %s index-pack <packfile>\n", argv[-1]); return EXIT_FAILURE; } if (git_indexer_new(&idx, ".", 0, NULL, NULL) < 0) { puts("bad idx"); return -1; } if ((fd = open(argv[1], 0)) < 0) { perror("open"); return -1; } do { read_bytes = read(fd, buf, sizeof(buf)); if (read_bytes < 0) break; if ((error = git_indexer_append(idx, buf, read_bytes, &stats)) < 0) goto cleanup; index_cb(&stats, NULL); } while (read_bytes > 0); if (read_bytes < 0) { error = -1; perror("failed reading"); goto cleanup; } if ((error = git_indexer_commit(idx, &stats)) < 0) goto cleanup; printf("\rIndexing %u of %u\n", stats.indexed_objects, stats.total_objects); puts(git_indexer_name(idx)); cleanup: close(fd); git_indexer_free(idx); return error; }
libgit2-main
examples/index-pack.c
/* * libgit2 "merge" example - shows how to perform merges * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" /** The following example demonstrates how to do merges with libgit2. * * It will merge whatever commit-ish you pass in into the current branch. * * Recognized options are : * --no-commit: don't actually commit the merge. * */ struct merge_options { const char **heads; size_t heads_count; git_annotated_commit **annotated; size_t annotated_count; int no_commit : 1; }; static void print_usage(void) { fprintf(stderr, "usage: merge [--no-commit] <commit...>\n"); exit(1); } static void merge_options_init(struct merge_options *opts) { memset(opts, 0, sizeof(*opts)); opts->heads = NULL; opts->heads_count = 0; opts->annotated = NULL; opts->annotated_count = 0; } static void opts_add_refish(struct merge_options *opts, const char *refish) { size_t sz; assert(opts != NULL); sz = ++opts->heads_count * sizeof(opts->heads[0]); opts->heads = xrealloc((void *) opts->heads, sz); opts->heads[opts->heads_count - 1] = refish; } static void parse_options(const char **repo_path, struct merge_options *opts, int argc, char **argv) { struct args_info args = ARGS_INFO_INIT; if (argc <= 1) print_usage(); for (args.pos = 1; args.pos < argc; ++args.pos) { const char *curr = argv[args.pos]; if (curr[0] != '-') { opts_add_refish(opts, curr); } else if (!strcmp(curr, "--no-commit")) { opts->no_commit = 1; } else if (match_str_arg(repo_path, &args, "--git-dir")) { continue; } else { print_usage(); } } } static int resolve_heads(git_repository *repo, struct merge_options *opts) { git_annotated_commit **annotated = calloc(opts->heads_count, sizeof(git_annotated_commit *)); size_t annotated_count = 0, i; int err = 0; for (i = 0; i < opts->heads_count; i++) { err = resolve_refish(&annotated[annotated_count++], repo, opts->heads[i]); if (err != 0) { fprintf(stderr, "failed to resolve refish %s: %s\n", opts->heads[i], git_error_last()->message); annotated_count--; continue; } } if (annotated_count != opts->heads_count) { fprintf(stderr, "unable to parse some refish\n"); free(annotated); return -1; } opts->annotated = annotated; opts->annotated_count = annotated_count; return 0; } static int perform_fastforward(git_repository *repo, const git_oid *target_oid, int is_unborn) { git_checkout_options ff_checkout_options = GIT_CHECKOUT_OPTIONS_INIT; git_reference *target_ref; git_reference *new_target_ref; git_object *target = NULL; int err = 0; if (is_unborn) { const char *symbolic_ref; git_reference *head_ref; /* HEAD reference is unborn, lookup manually so we don't try to resolve it */ err = git_reference_lookup(&head_ref, repo, "HEAD"); if (err != 0) { fprintf(stderr, "failed to lookup HEAD ref\n"); return -1; } /* Grab the reference HEAD should be pointing to */ symbolic_ref = git_reference_symbolic_target(head_ref); /* Create our master reference on the target OID */ err = git_reference_create(&target_ref, repo, symbolic_ref, target_oid, 0, NULL); if (err != 0) { fprintf(stderr, "failed to create master reference\n"); return -1; } git_reference_free(head_ref); } else { /* HEAD exists, just lookup and resolve */ err = git_repository_head(&target_ref, repo); if (err != 0) { fprintf(stderr, "failed to get HEAD reference\n"); return -1; } } /* Lookup the target object */ err = git_object_lookup(&target, repo, target_oid, GIT_OBJECT_COMMIT); if (err != 0) { fprintf(stderr, "failed to lookup OID %s\n", git_oid_tostr_s(target_oid)); return -1; } /* Checkout the result so the workdir is in the expected state */ ff_checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE; err = git_checkout_tree(repo, target, &ff_checkout_options); if (err != 0) { fprintf(stderr, "failed to checkout HEAD reference\n"); return -1; } /* Move the target reference to the target OID */ err = git_reference_set_target(&new_target_ref, target_ref, target_oid, NULL); if (err != 0) { fprintf(stderr, "failed to move HEAD reference\n"); return -1; } git_reference_free(target_ref); git_reference_free(new_target_ref); git_object_free(target); return 0; } static void output_conflicts(git_index *index) { git_index_conflict_iterator *conflicts; const git_index_entry *ancestor; const git_index_entry *our; const git_index_entry *their; int err = 0; check_lg2(git_index_conflict_iterator_new(&conflicts, index), "failed to create conflict iterator", NULL); while ((err = git_index_conflict_next(&ancestor, &our, &their, conflicts)) == 0) { fprintf(stderr, "conflict: a:%s o:%s t:%s\n", ancestor ? ancestor->path : "NULL", our->path ? our->path : "NULL", their->path ? their->path : "NULL"); } if (err != GIT_ITEROVER) { fprintf(stderr, "error iterating conflicts\n"); } git_index_conflict_iterator_free(conflicts); } static int create_merge_commit(git_repository *repo, git_index *index, struct merge_options *opts) { git_oid tree_oid, commit_oid; git_tree *tree; git_signature *sign; git_reference *merge_ref = NULL; git_annotated_commit *merge_commit; git_reference *head_ref; git_commit **parents = calloc(opts->annotated_count + 1, sizeof(git_commit *)); const char *msg_target = NULL; size_t msglen = 0; char *msg; size_t i; int err; /* Grab our needed references */ check_lg2(git_repository_head(&head_ref, repo), "failed to get repo HEAD", NULL); if (resolve_refish(&merge_commit, repo, opts->heads[0])) { fprintf(stderr, "failed to resolve refish %s", opts->heads[0]); free(parents); return -1; } /* Maybe that's a ref, so DWIM it */ err = git_reference_dwim(&merge_ref, repo, opts->heads[0]); check_lg2(err, "failed to DWIM reference", git_error_last()->message); /* Grab a signature */ check_lg2(git_signature_now(&sign, "Me", "[email protected]"), "failed to create signature", NULL); #define MERGE_COMMIT_MSG "Merge %s '%s'" /* Prepare a standard merge commit message */ if (merge_ref != NULL) { check_lg2(git_branch_name(&msg_target, merge_ref), "failed to get branch name of merged ref", NULL); } else { msg_target = git_oid_tostr_s(git_annotated_commit_id(merge_commit)); } msglen = snprintf(NULL, 0, MERGE_COMMIT_MSG, (merge_ref ? "branch" : "commit"), msg_target); if (msglen > 0) msglen++; msg = malloc(msglen); err = snprintf(msg, msglen, MERGE_COMMIT_MSG, (merge_ref ? "branch" : "commit"), msg_target); /* This is only to silence the compiler */ if (err < 0) goto cleanup; /* Setup our parent commits */ err = git_reference_peel((git_object **)&parents[0], head_ref, GIT_OBJECT_COMMIT); check_lg2(err, "failed to peel head reference", NULL); for (i = 0; i < opts->annotated_count; i++) { git_commit_lookup(&parents[i + 1], repo, git_annotated_commit_id(opts->annotated[i])); } /* Prepare our commit tree */ check_lg2(git_index_write_tree(&tree_oid, index), "failed to write merged tree", NULL); check_lg2(git_tree_lookup(&tree, repo, &tree_oid), "failed to lookup tree", NULL); /* Commit time ! */ err = git_commit_create(&commit_oid, repo, git_reference_name(head_ref), sign, sign, NULL, msg, tree, opts->annotated_count + 1, (const git_commit **)parents); check_lg2(err, "failed to create commit", NULL); /* We're done merging, cleanup the repository state */ git_repository_state_cleanup(repo); cleanup: free(parents); return err; } int lg2_merge(git_repository *repo, int argc, char **argv) { struct merge_options opts; git_index *index; git_repository_state_t state; git_merge_analysis_t analysis; git_merge_preference_t preference; const char *path = "."; int err = 0; merge_options_init(&opts); parse_options(&path, &opts, argc, argv); state = git_repository_state(repo); if (state != GIT_REPOSITORY_STATE_NONE) { fprintf(stderr, "repository is in unexpected state %d\n", state); goto cleanup; } err = resolve_heads(repo, &opts); if (err != 0) goto cleanup; err = git_merge_analysis(&analysis, &preference, repo, (const git_annotated_commit **)opts.annotated, opts.annotated_count); check_lg2(err, "merge analysis failed", NULL); if (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) { printf("Already up-to-date\n"); return 0; } else if (analysis & GIT_MERGE_ANALYSIS_UNBORN || (analysis & GIT_MERGE_ANALYSIS_FASTFORWARD && !(preference & GIT_MERGE_PREFERENCE_NO_FASTFORWARD))) { const git_oid *target_oid; if (analysis & GIT_MERGE_ANALYSIS_UNBORN) { printf("Unborn\n"); } else { printf("Fast-forward\n"); } /* Since this is a fast-forward, there can be only one merge head */ target_oid = git_annotated_commit_id(opts.annotated[0]); assert(opts.annotated_count == 1); return perform_fastforward(repo, target_oid, (analysis & GIT_MERGE_ANALYSIS_UNBORN)); } else if (analysis & GIT_MERGE_ANALYSIS_NORMAL) { git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT; git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; merge_opts.flags = 0; merge_opts.file_flags = GIT_MERGE_FILE_STYLE_DIFF3; checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE|GIT_CHECKOUT_ALLOW_CONFLICTS; if (preference & GIT_MERGE_PREFERENCE_FASTFORWARD_ONLY) { printf("Fast-forward is preferred, but only a merge is possible\n"); return -1; } err = git_merge(repo, (const git_annotated_commit **)opts.annotated, opts.annotated_count, &merge_opts, &checkout_opts); check_lg2(err, "merge failed", NULL); } /* If we get here, we actually performed the merge above */ check_lg2(git_repository_index(&index, repo), "failed to get repository index", NULL); if (git_index_has_conflicts(index)) { /* Handle conflicts */ output_conflicts(index); } else if (!opts.no_commit) { create_merge_commit(repo, index, &opts); printf("Merge made\n"); } cleanup: free((char **)opts.heads); free(opts.annotated); return 0; }
libgit2-main
examples/merge.c
/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev * * Additional changes are licensed under the same terms as NGINX and * copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "http_parser.h" #include <assert.h> #include <stddef.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <limits.h> #ifndef ULLONG_MAX # define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */ #endif #ifndef MIN # define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif #ifndef ARRAY_SIZE # define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif #ifndef BIT_AT # define BIT_AT(a, i) \ (!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \ (1 << ((unsigned int) (i) & 7)))) #endif #ifndef ELEM_AT # define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v)) #endif #define SET_ERRNO(e) \ do { \ parser->http_errno = (e); \ } while(0) /* Run the notify callback FOR, returning ER if it fails */ #define CALLBACK_NOTIFY_(FOR, ER) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (settings->on_##FOR) { \ if (0 != settings->on_##FOR(parser)) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ \ /* We either errored above or got paused; get out */ \ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { \ return (ER); \ } \ } \ } while (0) /* Run the notify callback FOR and consume the current byte */ #define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) /* Run the notify callback FOR and don't consume the current byte */ #define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) /* Run data callback FOR with LEN bytes, returning ER if it fails */ #define CALLBACK_DATA_(FOR, LEN, ER) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (FOR##_mark) { \ if (settings->on_##FOR) { \ if (0 != settings->on_##FOR(parser, FOR##_mark, (LEN))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ \ /* We either errored above or got paused; get out */ \ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { \ return (ER); \ } \ } \ FOR##_mark = NULL; \ } \ } while (0) /* Run the data callback FOR and consume the current byte */ #define CALLBACK_DATA(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) /* Run the data callback FOR and don't consume the current byte */ #define CALLBACK_DATA_NOADVANCE(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) /* Set the mark FOR; non-destructive if mark is already set */ #define MARK(FOR) \ do { \ if (!FOR##_mark) { \ FOR##_mark = p; \ } \ } while (0) #define PROXY_CONNECTION "proxy-connection" #define CONNECTION "connection" #define CONTENT_LENGTH "content-length" #define TRANSFER_ENCODING "transfer-encoding" #define UPGRADE "upgrade" #define CHUNKED "chunked" #define KEEP_ALIVE "keep-alive" #define CLOSE "close" static const char *method_strings[] = { #define XX(num, name, string) #string, HTTP_METHOD_MAP(XX) #undef XX }; /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1*<any CHAR except CTLs or separators> * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ static const char tokens[256] = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0, 0, 0, 0, 0, 0, 0, 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0, 0, 0, 0, 0, 0, 0, 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0, 0, 0, 0, 0, 0, 0, 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0, 0, 0, 0, 0, 0, 0, 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ 0, '!', 0, '#', '$', '%', '&', '\'', /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 0, 0, '*', '+', 0, '-', '.', 0, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ '0', '1', '2', '3', '4', '5', '6', '7', /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ '8', '9', 0, 0, 0, 0, 0, 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 'x', 'y', 'z', 0, 0, 0, '^', '_', /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 'x', 'y', 'z', 0, '|', 0, '~', 0 }; static const int8_t unhex[256] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; #if HTTP_PARSER_STRICT # define T(v) 0 #else # define T(v) v #endif static const uint8_t normal_url_char[32] = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128, /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, }; #undef T enum state { s_dead = 1 /* important that this is > 0 */ , s_start_req_or_res , s_res_or_resp_H , s_start_res , s_res_H , s_res_HT , s_res_HTT , s_res_HTTP , s_res_first_http_major , s_res_http_major , s_res_first_http_minor , s_res_http_minor , s_res_first_status_code , s_res_status_code , s_res_status , s_res_line_almost_done , s_start_req , s_req_method , s_req_spaces_before_url , s_req_schema , s_req_schema_slash , s_req_schema_slash_slash , s_req_server_start , s_req_server , s_req_server_with_at , s_req_path , s_req_query_string_start , s_req_query_string , s_req_fragment_start , s_req_fragment , s_req_http_start , s_req_http_H , s_req_http_HT , s_req_http_HTT , s_req_http_HTTP , s_req_first_http_major , s_req_http_major , s_req_first_http_minor , s_req_http_minor , s_req_line_almost_done , s_header_field_start , s_header_field , s_header_value_start , s_header_value , s_header_value_lws , s_header_almost_done , s_chunk_size_start , s_chunk_size , s_chunk_parameters , s_chunk_size_almost_done , s_headers_almost_done , s_headers_done /* Important: 's_headers_done' must be the last 'header' state. All * states beyond this must be 'body' states. It is used for overflow * checking. See the PARSING_HEADER() macro. */ , s_chunk_data , s_chunk_data_almost_done , s_chunk_data_done , s_body_identity , s_body_identity_eof , s_message_done }; #define PARSING_HEADER(state) (state <= s_headers_done) enum header_states { h_general = 0 , h_C , h_CO , h_CON , h_matching_connection , h_matching_proxy_connection , h_matching_content_length , h_matching_transfer_encoding , h_matching_upgrade , h_connection , h_content_length , h_transfer_encoding , h_upgrade , h_matching_transfer_encoding_chunked , h_matching_connection_keep_alive , h_matching_connection_close , h_transfer_encoding_chunked , h_connection_keep_alive , h_connection_close }; enum http_host_state { s_http_host_dead = 1 , s_http_userinfo_start , s_http_userinfo , s_http_host_start , s_http_host_v6_start , s_http_host , s_http_host_v6 , s_http_host_v6_end , s_http_host_port_start , s_http_host_port }; /* Macros for character classes; depends on strict-mode */ #define CR '\r' #define LF '\n' #define LOWER(c) (unsigned char)(c | 0x20) #define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') #define IS_NUM(c) ((c) >= '0' && (c) <= '9') #define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) #define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) #define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \ (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \ (c) == ')') #define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \ (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ (c) == '$' || (c) == ',') #if HTTP_PARSER_STRICT #define TOKEN(c) (tokens[(unsigned char)c]) #define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) #define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') #else #define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c]) #define IS_URL_CHAR(c) \ (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80)) #define IS_HOST_CHAR(c) \ (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') #endif #define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) #if HTTP_PARSER_STRICT # define STRICT_CHECK(cond) \ do { \ if (cond) { \ SET_ERRNO(HPE_STRICT); \ goto error; \ } \ } while (0) # define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) #else # define STRICT_CHECK(cond) # define NEW_MESSAGE() start_state #endif /* Map errno values to strings for human-readable output */ #define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s }, static struct { const char *name; const char *description; } http_strerror_tab[] = { HTTP_ERRNO_MAP(HTTP_STRERROR_GEN) }; #undef HTTP_STRERROR_GEN int http_message_needs_eof(const http_parser *parser); /* Our URL parser. * * This is designed to be shared by http_parser_execute() for URL validation, * hence it has a state transition + byte-for-byte interface. In addition, it * is meant to be embedded in http_parser_parse_url(), which does the dirty * work of turning state transitions URL components for its API. * * This function should only be invoked with non-space characters. It is * assumed that the caller cares about (and can detect) the transition between * URL and non-URL states by looking for these. */ static enum state parse_url_char(enum state s, const char ch) { if (ch == ' ' || ch == '\r' || ch == '\n') { return s_dead; } #if HTTP_PARSER_STRICT if (ch == '\t' || ch == '\f') { return s_dead; } #endif switch (s) { case s_req_spaces_before_url: /* Proxied requests are followed by scheme of an absolute URI (alpha). * All methods except CONNECT are followed by '/' or '*'. */ if (ch == '/' || ch == '*') { return s_req_path; } /* The schema must start with an alpha character. After that, it may * consist of digits, '+', '-' or '.', followed by a ':'. */ if (IS_ALPHA(ch)) { return s_req_schema; } break; case s_req_schema: if (IS_ALPHANUM(ch) || ch == '+' || ch == '-' || ch == '.') { return s; } if (ch == ':') { return s_req_schema_slash; } break; case s_req_schema_slash: if (ch == '/') { return s_req_schema_slash_slash; } break; case s_req_schema_slash_slash: if (ch == '/') { return s_req_server_start; } break; case s_req_server_with_at: if (ch == '@') { return s_dead; } /* FALLTHROUGH */ case s_req_server_start: case s_req_server: if (ch == '/') { return s_req_path; } if (ch == '?') { return s_req_query_string_start; } if (ch == '@') { return s_req_server_with_at; } if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') { return s_req_server; } break; case s_req_path: if (IS_URL_CHAR(ch)) { return s; } switch (ch) { case '?': return s_req_query_string_start; case '#': return s_req_fragment_start; } break; case s_req_query_string_start: case s_req_query_string: if (IS_URL_CHAR(ch)) { return s_req_query_string; } switch (ch) { case '?': /* allow extra '?' in query string */ return s_req_query_string; case '#': return s_req_fragment_start; } break; case s_req_fragment_start: if (IS_URL_CHAR(ch)) { return s_req_fragment; } switch (ch) { case '?': return s_req_fragment; case '#': return s; } break; case s_req_fragment: if (IS_URL_CHAR(ch)) { return s; } switch (ch) { case '?': case '#': return s; } break; default: break; } /* We should never fall out of the switch above unless there's an error */ return s_dead; } size_t http_parser_execute (http_parser *parser, const http_parser_settings *settings, const char *data, size_t len) { char c, ch; int8_t unhex_val; const char *p = data; const char *header_field_mark = 0; const char *header_value_mark = 0; const char *url_mark = 0; const char *body_mark = 0; /* We're in an error state. Don't bother doing anything. */ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { return 0; } if (len == 0) { switch (parser->state) { case s_body_identity_eof: /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if * we got paused. */ CALLBACK_NOTIFY_NOADVANCE(message_complete); return 0; case s_dead: case s_start_req_or_res: case s_start_res: case s_start_req: return 0; default: SET_ERRNO(HPE_INVALID_EOF_STATE); return 1; } } if (parser->state == s_header_field) header_field_mark = data; if (parser->state == s_header_value) header_value_mark = data; switch (parser->state) { case s_req_path: case s_req_schema: case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: case s_req_server: case s_req_server_with_at: case s_req_query_string_start: case s_req_query_string: case s_req_fragment_start: case s_req_fragment: url_mark = data; break; } for (p=data; p != data + len; p++) { ch = *p; if (PARSING_HEADER(parser->state)) { ++parser->nread; /* Buffer overflow attack */ if (parser->nread > HTTP_MAX_HEADER_SIZE) { SET_ERRNO(HPE_HEADER_OVERFLOW); goto error; } } reexecute_byte: switch (parser->state) { case s_dead: /* this state is used after a 'Connection: close' message * the parser will error out if it reads another message */ if (ch == CR || ch == LF) break; SET_ERRNO(HPE_CLOSED_CONNECTION); goto error; case s_start_req_or_res: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (ch == 'H') { parser->state = s_res_or_resp_H; CALLBACK_NOTIFY(message_begin); } else { parser->type = HTTP_REQUEST; parser->state = s_start_req; goto reexecute_byte; } break; } case s_res_or_resp_H: if (ch == 'T') { parser->type = HTTP_RESPONSE; parser->state = s_res_HT; } else { if (ch != 'E') { SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } parser->type = HTTP_REQUEST; parser->method = HTTP_HEAD; parser->index = 2; parser->state = s_req_method; } break; case s_start_res: { parser->flags = 0; parser->content_length = ULLONG_MAX; switch (ch) { case 'H': parser->state = s_res_H; break; case CR: case LF: break; default: SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } CALLBACK_NOTIFY(message_begin); break; } case s_res_H: STRICT_CHECK(ch != 'T'); parser->state = s_res_HT; break; case s_res_HT: STRICT_CHECK(ch != 'T'); parser->state = s_res_HTT; break; case s_res_HTT: STRICT_CHECK(ch != 'P'); parser->state = s_res_HTTP; break; case s_res_HTTP: STRICT_CHECK(ch != '/'); parser->state = s_res_first_http_major; break; case s_res_first_http_major: if (ch < '0' || ch > '9') { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major = ch - '0'; parser->state = s_res_http_major; break; /* major HTTP version or dot */ case s_res_http_major: { if (ch == '.') { parser->state = s_res_first_http_minor; break; } if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major *= 10; parser->http_major += ch - '0'; if (parser->http_major > 999) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } /* first digit of minor HTTP version */ case s_res_first_http_minor: if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor = ch - '0'; parser->state = s_res_http_minor; break; /* minor HTTP version or end of request line */ case s_res_http_minor: { if (ch == ' ') { parser->state = s_res_first_status_code; break; } if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor *= 10; parser->http_minor += ch - '0'; if (parser->http_minor > 999) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } case s_res_first_status_code: { if (!IS_NUM(ch)) { if (ch == ' ') { break; } SET_ERRNO(HPE_INVALID_STATUS); goto error; } parser->status_code = ch - '0'; parser->state = s_res_status_code; break; } case s_res_status_code: { if (!IS_NUM(ch)) { switch (ch) { case ' ': parser->state = s_res_status; break; case CR: parser->state = s_res_line_almost_done; break; case LF: parser->state = s_header_field_start; break; default: SET_ERRNO(HPE_INVALID_STATUS); goto error; } break; } parser->status_code *= 10; parser->status_code += ch - '0'; if (parser->status_code > 999) { SET_ERRNO(HPE_INVALID_STATUS); goto error; } break; } case s_res_status: /* the human readable status. e.g. "NOT FOUND" * we are not humans so just ignore this */ if (ch == CR) { parser->state = s_res_line_almost_done; break; } if (ch == LF) { parser->state = s_header_field_start; break; } break; case s_res_line_almost_done: STRICT_CHECK(ch != LF); parser->state = s_header_field_start; break; case s_start_req: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (!IS_ALPHA(ch)) { SET_ERRNO(HPE_INVALID_METHOD); goto error; } parser->method = (enum http_method) 0; parser->index = 1; switch (ch) { case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break; case 'D': parser->method = HTTP_DELETE; break; case 'G': parser->method = HTTP_GET; break; case 'H': parser->method = HTTP_HEAD; break; case 'L': parser->method = HTTP_LOCK; break; case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH */ break; case 'N': parser->method = HTTP_NOTIFY; break; case 'O': parser->method = HTTP_OPTIONS; break; case 'P': parser->method = HTTP_POST; /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ break; case 'R': parser->method = HTTP_REPORT; break; case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break; case 'T': parser->method = HTTP_TRACE; break; case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break; default: SET_ERRNO(HPE_INVALID_METHOD); goto error; } parser->state = s_req_method; CALLBACK_NOTIFY(message_begin); break; } case s_req_method: { const char *matcher; if (ch == '\0') { SET_ERRNO(HPE_INVALID_METHOD); goto error; } matcher = method_strings[parser->method]; if (ch == ' ' && matcher[parser->index] == '\0') { parser->state = s_req_spaces_before_url; } else if (ch == matcher[parser->index]) { ; /* nada */ } else if (parser->method == HTTP_CONNECT) { if (parser->index == 1 && ch == 'H') { parser->method = HTTP_CHECKOUT; } else if (parser->index == 2 && ch == 'P') { parser->method = HTTP_COPY; } else { goto error; } } else if (parser->method == HTTP_MKCOL) { if (parser->index == 1 && ch == 'O') { parser->method = HTTP_MOVE; } else if (parser->index == 1 && ch == 'E') { parser->method = HTTP_MERGE; } else if (parser->index == 1 && ch == '-') { parser->method = HTTP_MSEARCH; } else if (parser->index == 2 && ch == 'A') { parser->method = HTTP_MKACTIVITY; } else { goto error; } } else if (parser->method == HTTP_SUBSCRIBE) { if (parser->index == 1 && ch == 'E') { parser->method = HTTP_SEARCH; } else { goto error; } } else if (parser->index == 1 && parser->method == HTTP_POST) { if (ch == 'R') { parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */ } else if (ch == 'U') { parser->method = HTTP_PUT; /* or HTTP_PURGE */ } else if (ch == 'A') { parser->method = HTTP_PATCH; } else { goto error; } } else if (parser->index == 2) { if (parser->method == HTTP_PUT) { if (ch == 'R') parser->method = HTTP_PURGE; } else if (parser->method == HTTP_UNLOCK) { if (ch == 'S') parser->method = HTTP_UNSUBSCRIBE; } } else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') { parser->method = HTTP_PROPPATCH; } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } ++parser->index; break; } case s_req_spaces_before_url: { if (ch == ' ') break; MARK(url); if (parser->method == HTTP_CONNECT) { parser->state = s_req_server_start; } parser->state = parse_url_char((enum state)parser->state, ch); if (parser->state == s_dead) { SET_ERRNO(HPE_INVALID_URL); goto error; } break; } case s_req_schema: case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: { switch (ch) { /* No whitespace allowed here */ case ' ': case CR: case LF: SET_ERRNO(HPE_INVALID_URL); goto error; default: parser->state = parse_url_char((enum state)parser->state, ch); if (parser->state == s_dead) { SET_ERRNO(HPE_INVALID_URL); goto error; } } break; } case s_req_server: case s_req_server_with_at: case s_req_path: case s_req_query_string_start: case s_req_query_string: case s_req_fragment_start: case s_req_fragment: { switch (ch) { case ' ': parser->state = s_req_http_start; CALLBACK_DATA(url); break; case CR: case LF: parser->http_major = 0; parser->http_minor = 9; parser->state = (ch == CR) ? s_req_line_almost_done : s_header_field_start; CALLBACK_DATA(url); break; default: parser->state = parse_url_char((enum state)parser->state, ch); if (parser->state == s_dead) { SET_ERRNO(HPE_INVALID_URL); goto error; } } break; } case s_req_http_start: switch (ch) { case 'H': parser->state = s_req_http_H; break; case ' ': break; default: SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } break; case s_req_http_H: STRICT_CHECK(ch != 'T'); parser->state = s_req_http_HT; break; case s_req_http_HT: STRICT_CHECK(ch != 'T'); parser->state = s_req_http_HTT; break; case s_req_http_HTT: STRICT_CHECK(ch != 'P'); parser->state = s_req_http_HTTP; break; case s_req_http_HTTP: STRICT_CHECK(ch != '/'); parser->state = s_req_first_http_major; break; /* first digit of major HTTP version */ case s_req_first_http_major: if (ch < '1' || ch > '9') { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major = ch - '0'; parser->state = s_req_http_major; break; /* major HTTP version or dot */ case s_req_http_major: { if (ch == '.') { parser->state = s_req_first_http_minor; break; } if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major *= 10; parser->http_major += ch - '0'; if (parser->http_major > 999) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } /* first digit of minor HTTP version */ case s_req_first_http_minor: if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor = ch - '0'; parser->state = s_req_http_minor; break; /* minor HTTP version or end of request line */ case s_req_http_minor: { if (ch == CR) { parser->state = s_req_line_almost_done; break; } if (ch == LF) { parser->state = s_header_field_start; break; } /* XXX allow spaces after digit? */ if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor *= 10; parser->http_minor += ch - '0'; if (parser->http_minor > 999) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } break; } /* end of request line */ case s_req_line_almost_done: { if (ch != LF) { SET_ERRNO(HPE_LF_EXPECTED); goto error; } parser->state = s_header_field_start; break; } case s_header_field_start: { if (ch == CR) { parser->state = s_headers_almost_done; break; } if (ch == LF) { /* they might be just sending \n instead of \r\n so this would be * the second \n to denote the end of headers*/ parser->state = s_headers_almost_done; goto reexecute_byte; } c = TOKEN(ch); if (!c) { SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } MARK(header_field); parser->index = 0; parser->state = s_header_field; switch (c) { case 'c': parser->header_state = h_C; break; case 'p': parser->header_state = h_matching_proxy_connection; break; case 't': parser->header_state = h_matching_transfer_encoding; break; case 'u': parser->header_state = h_matching_upgrade; break; default: parser->header_state = h_general; break; } break; } case s_header_field: { c = TOKEN(ch); if (c) { switch (parser->header_state) { case h_general: break; case h_C: parser->index++; parser->header_state = (c == 'o' ? h_CO : h_general); break; case h_CO: parser->index++; parser->header_state = (c == 'n' ? h_CON : h_general); break; case h_CON: parser->index++; switch (c) { case 'n': parser->header_state = h_matching_connection; break; case 't': parser->header_state = h_matching_content_length; break; default: parser->header_state = h_general; break; } break; /* connection */ case h_matching_connection: parser->index++; if (parser->index > sizeof(CONNECTION)-1 || c != CONNECTION[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CONNECTION)-2) { parser->header_state = h_connection; } break; /* proxy-connection */ case h_matching_proxy_connection: parser->index++; if (parser->index > sizeof(PROXY_CONNECTION)-1 || c != PROXY_CONNECTION[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(PROXY_CONNECTION)-2) { parser->header_state = h_connection; } break; /* content-length */ case h_matching_content_length: parser->index++; if (parser->index > sizeof(CONTENT_LENGTH)-1 || c != CONTENT_LENGTH[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CONTENT_LENGTH)-2) { parser->header_state = h_content_length; } break; /* transfer-encoding */ case h_matching_transfer_encoding: parser->index++; if (parser->index > sizeof(TRANSFER_ENCODING)-1 || c != TRANSFER_ENCODING[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) { parser->header_state = h_transfer_encoding; } break; /* upgrade */ case h_matching_upgrade: parser->index++; if (parser->index > sizeof(UPGRADE)-1 || c != UPGRADE[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(UPGRADE)-2) { parser->header_state = h_upgrade; } break; case h_connection: case h_content_length: case h_transfer_encoding: case h_upgrade: if (ch != ' ') parser->header_state = h_general; break; default: assert(0 && "Unknown header_state"); break; } break; } if (ch == ':') { parser->state = s_header_value_start; CALLBACK_DATA(header_field); break; } if (ch == CR) { parser->state = s_header_almost_done; CALLBACK_DATA(header_field); break; } if (ch == LF) { parser->state = s_header_field_start; CALLBACK_DATA(header_field); break; } SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } case s_header_value_start: { if (ch == ' ' || ch == '\t') break; MARK(header_value); parser->state = s_header_value; parser->index = 0; if (ch == CR) { parser->header_state = h_general; parser->state = s_header_almost_done; CALLBACK_DATA(header_value); break; } if (ch == LF) { parser->state = s_header_field_start; CALLBACK_DATA(header_value); break; } c = LOWER(ch); switch (parser->header_state) { case h_upgrade: parser->flags |= F_UPGRADE; parser->header_state = h_general; break; case h_transfer_encoding: /* looking for 'Transfer-Encoding: chunked' */ if ('c' == c) { parser->header_state = h_matching_transfer_encoding_chunked; } else { parser->header_state = h_general; } break; case h_content_length: if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } parser->content_length = ch - '0'; break; case h_connection: /* looking for 'Connection: keep-alive' */ if (c == 'k') { parser->header_state = h_matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (c == 'c') { parser->header_state = h_matching_connection_close; } else { parser->header_state = h_general; } break; default: parser->header_state = h_general; break; } break; } case s_header_value: { if (ch == CR) { parser->state = s_header_almost_done; CALLBACK_DATA(header_value); break; } if (ch == LF) { parser->state = s_header_almost_done; CALLBACK_DATA_NOADVANCE(header_value); goto reexecute_byte; } c = LOWER(ch); switch (parser->header_state) { case h_general: break; case h_connection: case h_transfer_encoding: assert(0 && "Shouldn't get here."); break; case h_content_length: { uint64_t t; if (ch == ' ') break; if (!IS_NUM(ch)) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } t = parser->content_length; t *= 10; t += ch - '0'; /* Overflow? */ if (t < parser->content_length || t == ULLONG_MAX) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } parser->content_length = t; break; } /* Transfer-Encoding: chunked */ case h_matching_transfer_encoding_chunked: parser->index++; if (parser->index > sizeof(CHUNKED)-1 || c != CHUNKED[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CHUNKED)-2) { parser->header_state = h_transfer_encoding_chunked; } break; /* looking for 'Connection: keep-alive' */ case h_matching_connection_keep_alive: parser->index++; if (parser->index > sizeof(KEEP_ALIVE)-1 || c != KEEP_ALIVE[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(KEEP_ALIVE)-2) { parser->header_state = h_connection_keep_alive; } break; /* looking for 'Connection: close' */ case h_matching_connection_close: parser->index++; if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CLOSE)-2) { parser->header_state = h_connection_close; } break; case h_transfer_encoding_chunked: case h_connection_keep_alive: case h_connection_close: if (ch != ' ') parser->header_state = h_general; break; default: parser->state = s_header_value; parser->header_state = h_general; break; } break; } case s_header_almost_done: { STRICT_CHECK(ch != LF); parser->state = s_header_value_lws; switch (parser->header_state) { case h_connection_keep_alive: parser->flags |= F_CONNECTION_KEEP_ALIVE; break; case h_connection_close: parser->flags |= F_CONNECTION_CLOSE; break; case h_transfer_encoding_chunked: parser->flags |= F_CHUNKED; break; default: break; } break; } case s_header_value_lws: { if (ch == ' ' || ch == '\t') parser->state = s_header_value_start; else { parser->state = s_header_field_start; goto reexecute_byte; } break; } case s_headers_almost_done: { STRICT_CHECK(ch != LF); if (parser->flags & F_TRAILING) { /* End of a chunked request */ parser->state = NEW_MESSAGE(); CALLBACK_NOTIFY(message_complete); break; } parser->state = s_headers_done; /* Set this here so that on_headers_complete() callbacks can see it */ parser->upgrade = (parser->flags & F_UPGRADE || parser->method == HTTP_CONNECT); /* Here we call the headers_complete callback. This is somewhat * different than other callbacks because if the user returns 1, we * will interpret that as saying that this message has no body. This * is needed for the annoying case of recieving a response to a HEAD * request. * * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so * we have to simulate it by handling a change in errno below. */ if (settings->on_headers_complete) { switch (settings->on_headers_complete(parser)) { case 0: break; case 1: parser->flags |= F_SKIPBODY; break; default: SET_ERRNO(HPE_CB_headers_complete); return p - data; /* Error */ } } if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { return p - data; } goto reexecute_byte; } case s_headers_done: { STRICT_CHECK(ch != LF); parser->nread = 0; /* Exit, the rest of the connect is in a different protocol. */ if (parser->upgrade) { parser->state = NEW_MESSAGE(); CALLBACK_NOTIFY(message_complete); return (p - data) + 1; } if (parser->flags & F_SKIPBODY) { parser->state = NEW_MESSAGE(); CALLBACK_NOTIFY(message_complete); } else if (parser->flags & F_CHUNKED) { /* chunked encoding - ignore Content-Length header */ parser->state = s_chunk_size_start; } else { if (parser->content_length == 0) { /* Content-Length header given but zero: Content-Length: 0\r\n */ parser->state = NEW_MESSAGE(); CALLBACK_NOTIFY(message_complete); } else if (parser->content_length != ULLONG_MAX) { /* Content-Length header given and non-zero */ parser->state = s_body_identity; } else { if (parser->type == HTTP_REQUEST || !http_message_needs_eof(parser)) { /* Assume content-length 0 - read the next */ parser->state = NEW_MESSAGE(); CALLBACK_NOTIFY(message_complete); } else { /* Read body until EOF */ parser->state = s_body_identity_eof; } } } break; } case s_body_identity: { uint64_t to_read = MIN(parser->content_length, (uint64_t) ((data + len) - p)); assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); /* The difference between advancing content_length and p is because * the latter will automaticaly advance on the next loop iteration. * Further, if content_length ends up at 0, we want to see the last * byte again for our message complete callback. */ MARK(body); parser->content_length -= to_read; p += to_read - 1; if (parser->content_length == 0) { parser->state = s_message_done; /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. * * The alternative to doing this is to wait for the next byte to * trigger the data callback, just as in every other case. The * problem with this is that this makes it difficult for the test * harness to distinguish between complete-on-EOF and * complete-on-length. It's not clear that this distinction is * important for applications, but let's keep it for now. */ CALLBACK_DATA_(body, p - body_mark + 1, p - data); goto reexecute_byte; } break; } /* read until EOF */ case s_body_identity_eof: MARK(body); p = data + len - 1; break; case s_message_done: parser->state = NEW_MESSAGE(); CALLBACK_NOTIFY(message_complete); break; case s_chunk_size_start: { assert(parser->nread == 1); assert(parser->flags & F_CHUNKED); unhex_val = unhex[(unsigned char)ch]; if (unhex_val == -1) { SET_ERRNO(HPE_INVALID_CHUNK_SIZE); goto error; } parser->content_length = unhex_val; parser->state = s_chunk_size; break; } case s_chunk_size: { uint64_t t; assert(parser->flags & F_CHUNKED); if (ch == CR) { parser->state = s_chunk_size_almost_done; break; } unhex_val = unhex[(unsigned char)ch]; if (unhex_val == -1) { if (ch == ';' || ch == ' ') { parser->state = s_chunk_parameters; break; } SET_ERRNO(HPE_INVALID_CHUNK_SIZE); goto error; } t = parser->content_length; t *= 16; t += unhex_val; /* Overflow? */ if (t < parser->content_length || t == ULLONG_MAX) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } parser->content_length = t; break; } case s_chunk_parameters: { assert(parser->flags & F_CHUNKED); /* just ignore this. TODO check for overflow */ if (ch == CR) { parser->state = s_chunk_size_almost_done; break; } break; } case s_chunk_size_almost_done: { assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; if (parser->content_length == 0) { parser->flags |= F_TRAILING; parser->state = s_header_field_start; } else { parser->state = s_chunk_data; } break; } case s_chunk_data: { uint64_t to_read = MIN(parser->content_length, (uint64_t) ((data + len) - p)); assert(parser->flags & F_CHUNKED); assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); /* See the explanation in s_body_identity for why the content * length and data pointers are managed this way. */ MARK(body); parser->content_length -= to_read; p += to_read - 1; if (parser->content_length == 0) { parser->state = s_chunk_data_almost_done; } break; } case s_chunk_data_almost_done: assert(parser->flags & F_CHUNKED); assert(parser->content_length == 0); STRICT_CHECK(ch != CR); parser->state = s_chunk_data_done; CALLBACK_DATA(body); break; case s_chunk_data_done: assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; parser->state = s_chunk_size_start; break; default: assert(0 && "unhandled state"); SET_ERRNO(HPE_INVALID_INTERNAL_STATE); goto error; } } /* Run callbacks for any marks that we have leftover after we ran our of * bytes. There should be at most one of these set, so it's OK to invoke * them in series (unset marks will not result in callbacks). * * We use the NOADVANCE() variety of callbacks here because 'p' has already * overflowed 'data' and this allows us to correct for the off-by-one that * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' * value that's in-bounds). */ assert(((header_field_mark ? 1 : 0) + (header_value_mark ? 1 : 0) + (url_mark ? 1 : 0) + (body_mark ? 1 : 0)) <= 1); CALLBACK_DATA_NOADVANCE(header_field); CALLBACK_DATA_NOADVANCE(header_value); CALLBACK_DATA_NOADVANCE(url); CALLBACK_DATA_NOADVANCE(body); return len; error: if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { SET_ERRNO(HPE_UNKNOWN); } return (p - data); } /* Does the parser need to see an EOF to find the end of the message? */ int http_message_needs_eof (const http_parser *parser) { if (parser->type == HTTP_REQUEST) { return 0; } /* See RFC 2616 section 4.4 */ if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ parser->status_code == 204 || /* No Content */ parser->status_code == 304 || /* Not Modified */ parser->flags & F_SKIPBODY) { /* response to a HEAD request */ return 0; } if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { return 0; } return 1; } int http_should_keep_alive (const http_parser *parser) { if (parser->http_major > 0 && parser->http_minor > 0) { /* HTTP/1.1 */ if (parser->flags & F_CONNECTION_CLOSE) { return 0; } } else { /* HTTP/1.0 or earlier */ if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { return 0; } } return !http_message_needs_eof(parser); } const char * http_method_str (enum http_method m) { return ELEM_AT(method_strings, m, "<unknown>"); } void http_parser_init (http_parser *parser, enum http_parser_type t) { void *data = parser->data; /* preserve application data */ memset(parser, 0, sizeof(*parser)); parser->data = data; parser->type = t; parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); parser->http_errno = HPE_OK; } const char * http_errno_name(enum http_errno err) { assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0]))); return http_strerror_tab[err].name; } const char * http_errno_description(enum http_errno err) { assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0]))); return http_strerror_tab[err].description; } static enum http_host_state http_parse_host_char(enum http_host_state s, const char ch) { switch(s) { case s_http_userinfo: case s_http_userinfo_start: if (ch == '@') { return s_http_host_start; } if (IS_USERINFO_CHAR(ch)) { return s_http_userinfo; } break; case s_http_host_start: if (ch == '[') { return s_http_host_v6_start; } if (IS_HOST_CHAR(ch)) { return s_http_host; } break; case s_http_host: if (IS_HOST_CHAR(ch)) { return s_http_host; } /* FALLTHROUGH */ case s_http_host_v6_end: if (ch == ':') { return s_http_host_port_start; } break; case s_http_host_v6: if (ch == ']') { return s_http_host_v6_end; } /* FALLTHROUGH */ case s_http_host_v6_start: if (IS_HEX(ch) || ch == ':') { return s_http_host_v6; } break; case s_http_host_port: case s_http_host_port_start: if (IS_NUM(ch)) { return s_http_host_port; } break; default: break; } return s_http_host_dead; } static int http_parse_host(const char * buf, struct http_parser_url *u, int found_at) { enum http_host_state s; const char *p; size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; if (buflen > UINT16_MAX) return 1; u->field_data[UF_HOST].len = 0; s = found_at ? s_http_userinfo_start : s_http_host_start; for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) { enum http_host_state new_s = http_parse_host_char(s, *p); if (new_s == s_http_host_dead) { return 1; } switch(new_s) { case s_http_host: if (s != s_http_host) { u->field_data[UF_HOST].off = (uint16_t)(p - buf); } u->field_data[UF_HOST].len++; break; case s_http_host_v6: if (s != s_http_host_v6) { u->field_data[UF_HOST].off = (uint16_t)(p - buf); } u->field_data[UF_HOST].len++; break; case s_http_host_port: if (s != s_http_host_port) { u->field_data[UF_PORT].off = (uint16_t)(p - buf); u->field_data[UF_PORT].len = 0; u->field_set |= (1 << UF_PORT); } u->field_data[UF_PORT].len++; break; case s_http_userinfo: if (s != s_http_userinfo) { u->field_data[UF_USERINFO].off = (uint16_t)(p - buf); u->field_data[UF_USERINFO].len = 0; u->field_set |= (1 << UF_USERINFO); } u->field_data[UF_USERINFO].len++; break; default: break; } s = new_s; } /* Make sure we don't end somewhere unexpected */ switch (s) { case s_http_host_start: case s_http_host_v6_start: case s_http_host_v6: case s_http_userinfo: case s_http_userinfo_start: return 1; default: break; } return 0; } int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, struct http_parser_url *u) { enum state s; const char *p; enum http_parser_url_fields uf, old_uf; int found_at = 0; if (buflen > UINT16_MAX) return 1; u->port = u->field_set = 0; s = is_connect ? s_req_server_start : s_req_spaces_before_url; uf = old_uf = UF_MAX; for (p = buf; p < buf + buflen; p++) { s = parse_url_char(s, *p); /* Figure out the next field that we're operating on */ switch (s) { case s_dead: return 1; /* Skip delimeters */ case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: case s_req_query_string_start: case s_req_fragment_start: continue; case s_req_schema: uf = UF_SCHEMA; break; case s_req_server_with_at: found_at = 1; /* FALLTROUGH */ case s_req_server: uf = UF_HOST; break; case s_req_path: uf = UF_PATH; break; case s_req_query_string: uf = UF_QUERY; break; case s_req_fragment: uf = UF_FRAGMENT; break; default: assert(!"Unexpected state"); return 1; } /* Nothing's changed; soldier on */ if (uf == old_uf) { u->field_data[uf].len++; continue; } u->field_data[uf].off = (uint16_t)(p - buf); u->field_data[uf].len = 1; u->field_set |= (1 << uf); old_uf = uf; } /* host must be present if there is a schema */ /* parsing http:///toto will fail */ if ((u->field_set & ((1 << UF_SCHEMA) | (1 << UF_HOST))) != 0) { if (http_parse_host(buf, u, found_at) != 0) { return 1; } } /* CONNECT requests can only contain "hostname:port" */ if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) { return 1; } if (u->field_set & (1 << UF_PORT)) { /* Don't bother with endp; we've already validated the string */ unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10); /* Ports have a max value of 2^16 */ if (v > 0xffff) { return 1; } u->port = (uint16_t) v; } return 0; } void http_parser_pause(http_parser *parser, int paused) { /* Users should only be pausing/unpausing a parser that is not in an error * state. In non-debug builds, there's not much that we can do about this * other than ignore it. */ if (HTTP_PARSER_ERRNO(parser) == HPE_OK || HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); } else { assert(0 && "Attempting to pause parser in error state"); } } int http_body_is_final(const struct http_parser *parser) { return parser->state == s_message_done; }
libgit2-main
deps/http-parser/http_parser.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <arpa/inet.h> #include "ntlm.h" #include "unicode.h" #include "utf8.h" #include "crypt.h" #include "compat.h" #include "util.h" #define NTLM_ASSERT_ARG(expr) do { \ if (!(expr)) \ return NTLM_CLIENT_ERROR_INVALID_INPUT; \ } while(0) #define NTLM_ASSERT(ntlm, expr) do { \ if (!(expr)) { \ ntlm_client_set_errmsg(ntlm, "internal error: " #expr); \ return -1; \ } \ } while(0) unsigned char ntlm_client_signature[] = NTLM_SIGNATURE; static bool supports_unicode(ntlm_client *ntlm) { return (ntlm->flags & NTLM_CLIENT_DISABLE_UNICODE) ? false : true; } static inline bool increment_size(size_t *out, size_t incr) { if (SIZE_MAX - *out < incr) { *out = (size_t)-1; return false; } *out = *out + incr; return true; } ntlm_client *ntlm_client_init(ntlm_client_flags flags) { ntlm_client *ntlm = NULL; if ((ntlm = calloc(1, sizeof(ntlm_client))) == NULL) return NULL; ntlm->flags = flags; return ntlm; } #define ENSURE_INITIALIZED(ntlm) \ do { \ if (!(ntlm)->unicode_initialized) \ (ntlm)->unicode_initialized = ntlm_unicode_init((ntlm)); \ if (!(ntlm)->crypt_initialized) \ (ntlm)->crypt_initialized = ntlm_crypt_init((ntlm)); \ if (!(ntlm)->unicode_initialized || \ !(ntlm)->crypt_initialized) \ return -1; \ } while(0) void ntlm_client_set_errmsg(ntlm_client *ntlm, const char *errmsg) { ntlm->state = NTLM_STATE_ERROR; ntlm->errmsg = errmsg; } const char *ntlm_client_errmsg(ntlm_client *ntlm) { if (!ntlm) return "internal error"; return ntlm->errmsg ? ntlm->errmsg : "no error"; } int ntlm_client_set_version( ntlm_client *ntlm, uint8_t major, uint8_t minor, uint16_t build) { NTLM_ASSERT_ARG(ntlm); ntlm->host_version.major = major; ntlm->host_version.minor = minor; ntlm->host_version.build = build; ntlm->host_version.reserved = 0x0f000000; ntlm->flags |= NTLM_ENABLE_HOSTVERSION; return 0; } #define reset(ptr) do { free(ptr); ptr = NULL; } while(0) static void free_hostname(ntlm_client *ntlm) { reset(ntlm->hostname); reset(ntlm->hostdomain); reset(ntlm->hostname_utf16); ntlm->hostname_utf16_len = 0; } int ntlm_client_set_hostname( ntlm_client *ntlm, const char *hostname, const char *domain) { NTLM_ASSERT_ARG(ntlm); ENSURE_INITIALIZED(ntlm); free_hostname(ntlm); if (hostname && (ntlm->hostname = strdup(hostname)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (domain && (ntlm->hostdomain = strdup(domain)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (hostname && supports_unicode(ntlm) && !ntlm_unicode_utf8_to_16( &ntlm->hostname_utf16, &ntlm->hostname_utf16_len, ntlm, hostname, strlen(hostname))) return -1; return 0; } static void free_credentials(ntlm_client *ntlm) { if (ntlm->password) ntlm_memzero(ntlm->password, strlen(ntlm->password)); if (ntlm->password_utf16) ntlm_memzero(ntlm->password_utf16, ntlm->password_utf16_len); reset(ntlm->username); reset(ntlm->username_upper); reset(ntlm->userdomain); reset(ntlm->password); reset(ntlm->username_utf16); reset(ntlm->username_upper_utf16); reset(ntlm->userdomain_utf16); reset(ntlm->password_utf16); ntlm->username_utf16_len = 0; ntlm->username_upper_utf16_len = 0; ntlm->userdomain_utf16_len = 0; ntlm->password_utf16_len = 0; } int ntlm_client_set_credentials( ntlm_client *ntlm, const char *username, const char *domain, const char *password) { NTLM_ASSERT_ARG(ntlm); ENSURE_INITIALIZED(ntlm); free_credentials(ntlm); if ((username && (ntlm->username = strdup(username)) == NULL) || (domain && (ntlm->userdomain = strdup(domain)) == NULL) || (password && (ntlm->password = strdup(password)) == NULL)) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (username && supports_unicode(ntlm)) { if ((ntlm->username_upper = strdup(username)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } utf8upr(ntlm->username_upper); if (!ntlm_unicode_utf8_to_16( &ntlm->username_utf16, &ntlm->username_utf16_len, ntlm, ntlm->username, strlen(ntlm->username))) return -1; if (!ntlm_unicode_utf8_to_16( &ntlm->username_upper_utf16, &ntlm->username_upper_utf16_len, ntlm, ntlm->username_upper, strlen(ntlm->username_upper))) return -1; } if (domain && supports_unicode(ntlm) && !ntlm_unicode_utf8_to_16( &ntlm->userdomain_utf16, &ntlm->userdomain_utf16_len, ntlm, ntlm->userdomain, strlen(ntlm->userdomain))) return -1; return 0; } int ntlm_client_set_target(ntlm_client *ntlm, const char *target) { NTLM_ASSERT_ARG(ntlm); ENSURE_INITIALIZED(ntlm); free(ntlm->target); free(ntlm->target_utf16); ntlm->target = NULL; ntlm->target_utf16 = NULL; if (target) { if ((ntlm->target = strdup(target)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (supports_unicode(ntlm) && !ntlm_unicode_utf8_to_16( &ntlm->target_utf16, &ntlm->target_utf16_len, ntlm, ntlm->target, strlen(ntlm->target))) return -1; } return 0; } int ntlm_client_set_nonce(ntlm_client *ntlm, uint64_t nonce) { NTLM_ASSERT_ARG(ntlm); ntlm->nonce = nonce; return 0; } int ntlm_client_set_timestamp(ntlm_client *ntlm, uint64_t timestamp) { NTLM_ASSERT_ARG(ntlm); ntlm->timestamp = timestamp; return 0; } static inline bool write_buf( ntlm_client *ntlm, ntlm_buf *out, const unsigned char *buf, size_t len) { if (!len) return true; if (out->len - out->pos < len) { ntlm_client_set_errmsg(ntlm, "out of buffer space"); return false; } memcpy(&out->buf[out->pos], buf, len); out->pos += len; return true; } static inline bool write_byte( ntlm_client *ntlm, ntlm_buf *out, uint8_t value) { if (out->len - out->pos < 1) { ntlm_client_set_errmsg(ntlm, "out of buffer space"); return false; } out->buf[out->pos++] = value; return true; } static inline bool write_int16( ntlm_client *ntlm, ntlm_buf *out, uint16_t value) { if (out->len - out->pos < 2) { ntlm_client_set_errmsg(ntlm, "out of buffer space"); return false; } out->buf[out->pos++] = (value & 0x000000ff); out->buf[out->pos++] = (value & 0x0000ff00) >> 8; return true; } static inline bool write_int32( ntlm_client *ntlm, ntlm_buf *out, uint32_t value) { if (out->len - out->pos < 2) { ntlm_client_set_errmsg(ntlm, "out of buffer space"); return false; } out->buf[out->pos++] = (value & 0x000000ff); out->buf[out->pos++] = (value & 0x0000ff00) >> 8; out->buf[out->pos++] = (value & 0x00ff0000) >> 16; out->buf[out->pos++] = (value & 0xff000000) >> 24; return true; } static inline bool write_version( ntlm_client *ntlm, ntlm_buf *out, ntlm_version *version) { return write_byte(ntlm, out, version->major) && write_byte(ntlm, out, version->minor) && write_int16(ntlm, out, version->build) && write_int32(ntlm, out, version->reserved); } static inline bool write_bufinfo( ntlm_client *ntlm, ntlm_buf *out, size_t len, size_t offset) { if (len > UINT16_MAX) { ntlm_client_set_errmsg(ntlm, "invalid string, too long"); return false; } if (offset > UINT32_MAX) { ntlm_client_set_errmsg(ntlm, "invalid string, invalid offset"); return false; } return write_int16(ntlm, out, (uint16_t)len) && write_int16(ntlm, out, (uint16_t)len) && write_int32(ntlm, out, (uint32_t)offset); } static inline bool read_buf( unsigned char *out, ntlm_client *ntlm, ntlm_buf *message, size_t len) { if (message->len - message->pos < len) { ntlm_client_set_errmsg(ntlm, "truncated message"); return false; } memcpy(out, &message->buf[message->pos], len); message->pos += len; return true; } static inline bool read_byte( uint8_t *out, ntlm_client *ntlm, ntlm_buf *message) { if (message->len - message->pos < 1) { ntlm_client_set_errmsg(ntlm, "truncated message"); return false; } *out = message->buf[message->pos++]; return true; } static inline bool read_int16( uint16_t *out, ntlm_client *ntlm, ntlm_buf *message) { if (message->len - message->pos < 2) { ntlm_client_set_errmsg(ntlm, "truncated message"); return false; } *out = ((message->buf[message->pos] & 0xff)) | ((message->buf[message->pos+1] & 0xff) << 8); message->pos += 2; return true; } static inline bool read_int32( uint32_t *out, ntlm_client *ntlm, ntlm_buf *message) { if (message->len - message->pos < 4) { ntlm_client_set_errmsg(ntlm, "truncated message"); return false; } *out = ((message->buf[message->pos] & 0xff)) | ((message->buf[message->pos+1] & 0xff) << 8) | ((message->buf[message->pos+2] & 0xff) << 16) | ((message->buf[message->pos+3] & 0xff) << 24); message->pos += 4; return true; } static inline bool read_int64( uint64_t *out, ntlm_client *ntlm, ntlm_buf *message) { if (message->len - message->pos < 8) { ntlm_client_set_errmsg(ntlm, "truncated message"); return false; } *out = ((uint64_t)(message->buf[message->pos] & 0xff)) | ((uint64_t)(message->buf[message->pos+1] & 0xff) << 8) | ((uint64_t)(message->buf[message->pos+2] & 0xff) << 16) | ((uint64_t)(message->buf[message->pos+3] & 0xff) << 24) | ((uint64_t)(message->buf[message->pos+4] & 0xff) << 32) | ((uint64_t)(message->buf[message->pos+5] & 0xff) << 40) | ((uint64_t)(message->buf[message->pos+6] & 0xff) << 48) | ((uint64_t)(message->buf[message->pos+7] & 0xff) << 56); message->pos += 8; return true; } static inline bool read_version( ntlm_version *out, ntlm_client *ntlm, ntlm_buf *message) { return read_byte(&out->major, ntlm, message) && read_byte(&out->minor, ntlm, message) && read_int16(&out->build, ntlm, message) && read_int32(&out->reserved, ntlm, message); } static inline bool read_bufinfo( uint16_t *out_len, uint32_t *out_offset, ntlm_client *ntlm, ntlm_buf *message) { uint16_t allocated; return read_int16(out_len, ntlm, message) && read_int16(&allocated, ntlm, message) && read_int32(out_offset, ntlm, message); } static inline bool read_string_unicode( char **out, ntlm_client *ntlm, ntlm_buf *message, uint8_t string_len) { size_t out_len; int ret = ntlm_unicode_utf16_to_8(out, &out_len, ntlm, (char *)&message->buf[message->pos], string_len); message->pos += string_len; return ret; } static inline bool read_string_ascii( char **out, ntlm_client *ntlm, ntlm_buf *message, uint8_t string_len) { char *str; if ((str = malloc(string_len + 1)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return false; } memcpy(str, &message->buf[message->pos], string_len); str[string_len] = '\0'; message->pos += string_len; *out = str; return true; } static inline bool read_string( char **out, ntlm_client *ntlm, ntlm_buf *message, uint8_t string_len, bool unicode) { if (unicode) return read_string_unicode(out, ntlm, message, string_len); else return read_string_ascii(out, ntlm, message, string_len); } static inline bool read_target_info( char **server_out, char **domain_out, char **server_dns_out, char **domain_dns_out, ntlm_client *ntlm, ntlm_buf *message, bool unicode) { uint16_t block_type, block_len; bool done = false; *server_out = NULL; *domain_out = NULL; *server_dns_out = NULL; *domain_dns_out = NULL; while (!done && (message->len - message->pos) >= 4) { if (!read_int16(&block_type, ntlm, message) || !read_int16(&block_len, ntlm, message)) { ntlm_client_set_errmsg(ntlm, "truncated target info block"); return false; } if (!block_type && block_len) { ntlm_client_set_errmsg(ntlm, "invalid target info block"); return -1; } switch (block_type) { case NTLM_TARGET_INFO_DOMAIN: if (!read_string(domain_out, ntlm, message, block_len, unicode)) return -1; break; case NTLM_TARGET_INFO_SERVER: if (!read_string(server_out, ntlm, message, block_len, unicode)) return -1; break; case NTLM_TARGET_INFO_DOMAIN_DNS: if (!read_string(domain_dns_out, ntlm, message, block_len, unicode)) return -1; break; case NTLM_TARGET_INFO_SERVER_DNS: if (!read_string(server_dns_out, ntlm, message, block_len, unicode)) return -1; break; case NTLM_TARGET_INFO_END: done = true; break; default: ntlm_client_set_errmsg(ntlm, "unknown target info block type"); return -1; } } if (message->len != message->pos) { ntlm_client_set_errmsg(ntlm, "invalid extra data in target info section"); return false; } return true; } int ntlm_client_negotiate( const unsigned char **out, size_t *out_len, ntlm_client *ntlm) { size_t hostname_len, domain_len; size_t domain_offset = 0; size_t hostname_offset = 0; uint32_t flags = 0; NTLM_ASSERT_ARG(out); NTLM_ASSERT_ARG(out_len); NTLM_ASSERT_ARG(ntlm); *out = NULL; *out_len = 0; if (ntlm->state != NTLM_STATE_NEGOTIATE) { ntlm_client_set_errmsg(ntlm, "ntlm handle in invalid state"); return -1; } flags |= NTLM_NEGOTIATE_OEM; if (supports_unicode(ntlm)) flags |= NTLM_NEGOTIATE_UNICODE; if (!(ntlm->flags & NTLM_CLIENT_DISABLE_NTLM2) || (ntlm->flags & NTLM_CLIENT_ENABLE_NTLM)) flags |= NTLM_NEGOTIATE_NTLM; if (!(ntlm->flags & NTLM_CLIENT_DISABLE_REQUEST_TARGET)) flags |= NTLM_NEGOTIATE_REQUEST_TARGET; hostname_len = ntlm->hostname ? strlen(ntlm->hostname) : 0; domain_len = ntlm->hostdomain ? strlen(ntlm->hostdomain) : 0; /* Minimum header size */ ntlm->negotiate.len = 16; /* Include space for security buffer descriptors */ if (domain_len) increment_size(&ntlm->negotiate.len, 8); if (hostname_len) increment_size(&ntlm->negotiate.len, 8); if (ntlm->flags & NTLM_ENABLE_HOSTVERSION) increment_size(&ntlm->negotiate.len, 8); /* Location of security buffers */ if (hostname_len) { flags |= NTLM_NEGOTIATE_WORKSTATION_SUPPLIED; hostname_offset = ntlm->negotiate.len; increment_size(&ntlm->negotiate.len, hostname_len); } if (domain_len) { flags |= NTLM_NEGOTIATE_DOMAIN_SUPPLIED; domain_offset = ntlm->negotiate.len; increment_size(&ntlm->negotiate.len, domain_len); } if (ntlm->negotiate.len == (size_t)-1) { ntlm_client_set_errmsg(ntlm, "message too large"); return -1; } if ((ntlm->negotiate.buf = calloc(1, ntlm->negotiate.len)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (!write_buf(ntlm, &ntlm->negotiate, ntlm_client_signature, sizeof(ntlm_client_signature)) || !write_int32(ntlm, &ntlm->negotiate, 1) || !write_int32(ntlm, &ntlm->negotiate, flags)) return -1; /* Domain information */ if (domain_len > 0 && !write_bufinfo(ntlm, &ntlm->negotiate, domain_len, domain_offset)) return -1; /* Workstation information */ if (hostname_len > 0 && !write_bufinfo(ntlm, &ntlm->negotiate, hostname_len, hostname_offset)) return -1; /* Version number */ if (!!(ntlm->flags & NTLM_ENABLE_HOSTVERSION) && !write_version(ntlm, &ntlm->negotiate, &ntlm->host_version)) return -1; if (hostname_len > 0) { NTLM_ASSERT(ntlm, hostname_offset == ntlm->negotiate.pos); if (!write_buf(ntlm, &ntlm->negotiate, (const unsigned char *)ntlm->hostname, hostname_len)) return -1; } if (domain_len > 0) { NTLM_ASSERT(ntlm, domain_offset == ntlm->negotiate.pos); if (!write_buf(ntlm, &ntlm->negotiate, (const unsigned char *)ntlm->hostdomain, domain_len)) return -1; } NTLM_ASSERT(ntlm, ntlm->negotiate.pos == ntlm->negotiate.len); ntlm->state = NTLM_STATE_CHALLENGE; *out = ntlm->negotiate.buf; *out_len = ntlm->negotiate.len; return 0; } int ntlm_client_set_challenge( ntlm_client *ntlm, const unsigned char *challenge_msg, size_t challenge_msg_len) { unsigned char signature[8]; ntlm_buf challenge; uint32_t type_indicator, header_end; uint16_t name_len, info_len = 0; uint32_t name_offset, info_offset = 0; bool unicode, has_target_info = false; NTLM_ASSERT_ARG(ntlm); NTLM_ASSERT_ARG(challenge_msg || !challenge_msg_len); ENSURE_INITIALIZED(ntlm); if (ntlm->state != NTLM_STATE_NEGOTIATE && ntlm->state != NTLM_STATE_CHALLENGE) { ntlm_client_set_errmsg(ntlm, "ntlm handle in invalid state"); return -1; } challenge.buf = (unsigned char *)challenge_msg; challenge.len = challenge_msg_len; challenge.pos = 0; if (!read_buf(signature, ntlm, &challenge, 8) || !read_int32(&type_indicator, ntlm, &challenge) || !read_bufinfo(&name_len, &name_offset, ntlm, &challenge) || !read_int32(&ntlm->challenge.flags, ntlm, &challenge) || !read_int64(&ntlm->challenge.nonce, ntlm, &challenge)) return -1; if (memcmp(signature, ntlm_client_signature, sizeof(ntlm_client_signature)) != 0) { ntlm_client_set_errmsg(ntlm, "invalid message signature"); return -1; } if (type_indicator != 2) { ntlm_client_set_errmsg(ntlm, "invalid message indicator"); return -1; } /* * If there's additional space before the data section, that's the * target information description section. */ header_end = challenge.len; if (name_offset && name_offset < header_end) header_end = name_offset; if ((header_end - challenge.pos) >= 16) { has_target_info = true; } if (!has_target_info && (ntlm->challenge.flags & NTLM_NEGOTIATE_TARGET_INFO)) { ntlm_client_set_errmsg(ntlm, "truncated message; expected target info"); return -1; } /* * If there's a target info section then advanced over the reserved * space and read the target information. */ if (has_target_info) { uint64_t reserved; if (!read_int64(&reserved, ntlm, &challenge)) { ntlm_client_set_errmsg(ntlm, "truncated message; expected reserved space"); return -1; } if (reserved != 0) { ntlm_client_set_errmsg(ntlm, "invalid message; expected reserved space to be empty"); return -1; } if (!read_bufinfo(&info_len, &info_offset, ntlm, &challenge)) { ntlm_client_set_errmsg(ntlm, "truncated message; expected target info"); return -1; } } unicode = !!(ntlm->challenge.flags & NTLM_NEGOTIATE_UNICODE); /* * If there's still additional space before the data section, * that's the server's version information. */ if (info_offset && info_offset < header_end) header_end = info_offset; if (ntlm->challenge.flags & NTLM_NEGOTIATE_VERSION) { if ((header_end - challenge.pos) != sizeof(ntlm_version) || !read_version(&ntlm->challenge.target_version, ntlm, &challenge)) { ntlm_client_set_errmsg(ntlm, "truncated message; expected version"); return -1; } } /* validate data section */ if ((name_offset && name_offset < challenge.pos) || challenge.len < name_len || (challenge.len - name_len) < name_offset) { ntlm_client_set_errmsg(ntlm, "invalid message; invalid target name buffer"); return -1; } if ((info_offset && info_offset < challenge.pos) || challenge.len < info_len || (challenge.len - info_len) < info_offset) { ntlm_client_set_errmsg(ntlm, "invalid message; invalid target info buffer"); return -1; } /* advance to the data section */ if (name_len && name_offset) { challenge.pos = name_offset; if (!read_string(&ntlm->challenge.target, ntlm, &challenge, name_len, unicode)) { ntlm_client_set_errmsg(ntlm, "truncated message; truncated target name"); return -1; } } if (info_len && info_offset) { ntlm_buf info_buf; challenge.pos = info_offset; /* create a copy of the target info; we need the literal data */ if ((ntlm->challenge.target_info = malloc(info_len)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (!read_buf(ntlm->challenge.target_info, ntlm, &challenge, info_len)) { ntlm_client_set_errmsg(ntlm, "truncated message; truncated target info"); return -1; } info_buf.buf = ntlm->challenge.target_info; info_buf.pos = 0; info_buf.len = info_len; /* then set up the target info and parse it */ if (!read_target_info(&ntlm->challenge.target_server, &ntlm->challenge.target_domain, &ntlm->challenge.target_server_dns, &ntlm->challenge.target_domain_dns, ntlm, &info_buf, unicode)) return -1; ntlm->challenge.target_info_len = info_len; } ntlm->state = NTLM_STATE_RESPONSE; return 0; } uint64_t ntlm_client_challenge_nonce(ntlm_client *ntlm) { return ntlm->challenge.nonce; } const char *ntlm_client_target(ntlm_client *ntlm) { return ntlm->challenge.target; } const char *ntlm_client_target_server(ntlm_client *ntlm) { return ntlm->challenge.target_server; } const char *ntlm_client_target_domain(ntlm_client *ntlm) { return ntlm->challenge.target_domain; } const char *ntlm_client_target_server_dns(ntlm_client *ntlm) { return ntlm->challenge.target_server_dns; } const char *ntlm_client_target_domain_dns(ntlm_client *ntlm) { return ntlm->challenge.target_domain_dns; } #define EVEN_PARITY(a) \ (!!((a) & INT64_C(0x01)) ^ !!((a) & INT64_C(0x02)) ^ \ !!((a) & INT64_C(0x04)) ^ !!((a) & INT64_C(0x08)) ^ \ !!((a) & INT64_C(0x10)) ^ !!((a) & INT64_C(0x20)) ^ \ !!((a) & INT64_C(0x40)) ^ !!((a) & INT64_C(0x80))) static void generate_odd_parity(ntlm_des_block *block) { size_t i; for (i = 0; i < sizeof(ntlm_des_block); i++) (*block)[i] |= (1 ^ EVEN_PARITY((*block)[i])); } static void des_key_from_password( ntlm_des_block *out, const unsigned char *plaintext, size_t plaintext_len) { size_t i; plaintext_len = MIN(plaintext_len, 7); memset(*out, 0, sizeof(ntlm_des_block)); for (i = 0; i < plaintext_len; i++) { size_t j = (7 - i); uint8_t mask = (0xff >> j); (*out)[i] |= ((plaintext[i] & (0xff - mask)) >> i); (*out)[i+1] |= ((plaintext[i] & mask) << j); } generate_odd_parity(out); } static inline bool generate_lm_hash( ntlm_des_block out[2], ntlm_client *ntlm, const char *password) { /* LM encrypts this known plaintext using the password as a key */ ntlm_des_block plaintext = NTLM_LM_PLAINTEXT; ntlm_des_block keystr1, keystr2; size_t keystr1_len, keystr2_len; ntlm_des_block key1, key2; size_t password_len, i; /* Copy the first 14 characters of the password, uppercased */ memset(&keystr1, 0, sizeof(keystr1)); memset(&keystr2, 0, sizeof(keystr2)); password_len = password ? strlen(password) : 0; /* Split the password into two 7 byte chunks */ keystr1_len = MIN(7, password_len); keystr2_len = (password_len > 7) ? MIN(14, password_len) - 7 : 0; for (i = 0; i < keystr1_len; i++) keystr1[i] = (unsigned char)toupper(password[i]); for (i = 0; i < keystr2_len; i++) keystr2[i] = (unsigned char)toupper(password[i+7]); /* DES encrypt the LM constant using the password as the key */ des_key_from_password(&key1, keystr1, keystr1_len); des_key_from_password(&key2, keystr2, keystr2_len); return ntlm_des_encrypt(&out[0], ntlm, &plaintext, &key1) && ntlm_des_encrypt(&out[1], ntlm, &plaintext, &key2); } static void des_keys_from_lm_hash(ntlm_des_block out[3], ntlm_des_block lm_hash[2]) { ntlm_des_block split[3]; memcpy(&split[0][0], &lm_hash[0][0], 7); memcpy(&split[1][0], &lm_hash[0][7], 1); memcpy(&split[1][1], &lm_hash[1][0], 6); memcpy(&split[2][0], &lm_hash[1][6], 2); des_key_from_password(&out[0], split[0], 7); des_key_from_password(&out[1], split[1], 7); des_key_from_password(&out[2], split[2], 2); } static bool generate_lm_response(ntlm_client *ntlm) { ntlm_des_block lm_hash[2], key[3], lm_response[3]; ntlm_des_block *challenge = (ntlm_des_block *)&ntlm->challenge.nonce; /* Generate the LM hash from the password */ if (!generate_lm_hash(lm_hash, ntlm, ntlm->password)) return false; /* Convert that LM hash to three DES keys */ des_keys_from_lm_hash(key, lm_hash); /* Finally, encrypt the challenge with each of these keys */ if (!ntlm_des_encrypt(&lm_response[0], ntlm, challenge, &key[0]) || !ntlm_des_encrypt(&lm_response[1], ntlm, challenge, &key[1]) || !ntlm_des_encrypt(&lm_response[2], ntlm, challenge, &key[2])) return false; memcpy(&ntlm->lm_response[0], lm_response[0], 8); memcpy(&ntlm->lm_response[8], lm_response[1], 8); memcpy(&ntlm->lm_response[16], lm_response[2], 8); ntlm->lm_response_len = sizeof(ntlm->lm_response); return true; } static bool generate_ntlm_hash( unsigned char out[NTLM_NTLM_HASH_LEN], ntlm_client *ntlm) { /* Generate the LM hash from the (Unicode) password */ if (ntlm->password && !ntlm_unicode_utf8_to_16( &ntlm->password_utf16, &ntlm->password_utf16_len, ntlm, ntlm->password, strlen(ntlm->password))) return false; return ntlm_md4_digest(out, ntlm, (const unsigned char *)ntlm->password_utf16, ntlm->password_utf16_len); } static bool generate_ntlm_response(ntlm_client *ntlm) { unsigned char ntlm_hash[NTLM_NTLM_HASH_LEN] = {0}; ntlm_des_block key[3], ntlm_response[3]; ntlm_des_block *challenge = (ntlm_des_block *)&ntlm->challenge.nonce; if (!generate_ntlm_hash(ntlm_hash, ntlm)) return false; /* Convert that LM hash to three DES keys */ des_key_from_password(&key[0], &ntlm_hash[0], 7); des_key_from_password(&key[1], &ntlm_hash[7], 7); des_key_from_password(&key[2], &ntlm_hash[14], 2); /* Finally, encrypt the challenge with each of these keys */ if (!ntlm_des_encrypt(&ntlm_response[0], ntlm, challenge, &key[0]) || !ntlm_des_encrypt(&ntlm_response[1], ntlm, challenge, &key[1]) || !ntlm_des_encrypt(&ntlm_response[2], ntlm, challenge, &key[2])) return false; memcpy(&ntlm->ntlm_response[0], ntlm_response[0], 8); memcpy(&ntlm->ntlm_response[8], ntlm_response[1], 8); memcpy(&ntlm->ntlm_response[16], ntlm_response[2], 8); ntlm->ntlm_response_len = sizeof(ntlm->ntlm_response); return true; } static bool generate_ntlm2_hash( unsigned char out[NTLM_NTLM2_HASH_LEN], ntlm_client *ntlm) { unsigned char ntlm_hash[NTLM_NTLM_HASH_LEN] = {0}; const unsigned char *username = NULL, *target = NULL; size_t username_len = 0, target_len = 0, out_len = NTLM_NTLM2_HASH_LEN; if (!generate_ntlm_hash(ntlm_hash, ntlm)) return false; if (ntlm->username_upper_utf16) { username = (const unsigned char *)ntlm->username_upper_utf16; username_len = ntlm->username_upper_utf16_len; } if (ntlm->target_utf16) { target = (const unsigned char *)ntlm->target_utf16; target_len = ntlm->target_utf16_len; } if (!ntlm_hmac_md5_init(ntlm, ntlm_hash, sizeof(ntlm_hash)) || !ntlm_hmac_md5_update(ntlm, username, username_len) || !ntlm_hmac_md5_update(ntlm, target, target_len) || !ntlm_hmac_md5_final(out, &out_len, ntlm)) { ntlm_client_set_errmsg(ntlm, "failed to create HMAC-MD5"); return false; } NTLM_ASSERT(ntlm, out_len == NTLM_NTLM2_HASH_LEN); return true; } static bool generate_ntlm2_challengehash( unsigned char out[16], ntlm_client *ntlm, unsigned char ntlm2_hash[NTLM_NTLM2_HASH_LEN], const unsigned char *blob, size_t blob_len) { size_t out_len = 16; if (!ntlm_hmac_md5_init(ntlm, ntlm2_hash, NTLM_NTLM2_HASH_LEN) || !ntlm_hmac_md5_update(ntlm, (const unsigned char *)&ntlm->challenge.nonce, 8) || !ntlm_hmac_md5_update(ntlm, blob, blob_len) || !ntlm_hmac_md5_final(out, &out_len, ntlm)) { ntlm_client_set_errmsg(ntlm, "failed to create HMAC-MD5"); return false; } NTLM_ASSERT(ntlm, out_len == 16); return true; } static bool generate_lm2_response(ntlm_client *ntlm, unsigned char ntlm2_hash[NTLM_NTLM2_HASH_LEN]) { unsigned char lm2_challengehash[16] = {0}; size_t lm2_len = 16; uint64_t local_nonce; local_nonce = ntlm_htonll(ntlm->nonce); if (!ntlm_hmac_md5_init(ntlm, ntlm2_hash, NTLM_NTLM2_HASH_LEN) || !ntlm_hmac_md5_update(ntlm, (const unsigned char *)&ntlm->challenge.nonce, 8) || !ntlm_hmac_md5_update(ntlm, (const unsigned char *)&local_nonce, 8) || !ntlm_hmac_md5_final(lm2_challengehash, &lm2_len, ntlm)) { ntlm_client_set_errmsg(ntlm, "failed to create HMAC-MD5"); return false; } NTLM_ASSERT(ntlm, lm2_len == 16); memcpy(&ntlm->lm_response[0], lm2_challengehash, 16); memcpy(&ntlm->lm_response[16], &local_nonce, 8); ntlm->lm_response_len = 24; return true; } static bool generate_timestamp(ntlm_client *ntlm) { if (!ntlm->timestamp) ntlm->timestamp = (time(NULL) + 11644473600) * 10000000; return true; } static bool generate_nonce(ntlm_client *ntlm) { unsigned char buf[8]; if (ntlm->nonce) return true; if (!ntlm_random_bytes(buf, ntlm, 8)) return false; memcpy(&ntlm->nonce, buf, sizeof(uint64_t)); return true; } static bool generate_ntlm2_response(ntlm_client *ntlm) { size_t blob_len, ntlm2_response_len; uint32_t signature; uint64_t timestamp, nonce; unsigned char ntlm2_hash[NTLM_NTLM2_HASH_LEN]; unsigned char challengehash[16] = {0}; unsigned char *blob; if (!generate_timestamp(ntlm) || !generate_nonce(ntlm) || !generate_ntlm2_hash(ntlm2_hash, ntlm)) return false; blob_len = ntlm->challenge.target_info_len + 32; ntlm2_response_len = blob_len + 16; if ((ntlm->ntlm2_response = malloc(ntlm2_response_len)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return false; } /* position the blob in the response; we'll use it then return it */ blob = ntlm->ntlm2_response + 16; /* the blob's integer values are in network byte order */ signature = htonl(0x01010000); timestamp = ntlm_htonll(ntlm->timestamp); nonce = ntlm_htonll(ntlm->nonce); /* construct the blob */ memcpy(&blob[0], &signature, 4); memset(&blob[4], 0, 4); memcpy(&blob[8], &timestamp, 8); memcpy(&blob[16], &nonce, 8); memset(&blob[24], 0, 4); memcpy(&blob[28], ntlm->challenge.target_info, ntlm->challenge.target_info_len); memset(&blob[28 + ntlm->challenge.target_info_len], 0, 4); if (!generate_ntlm2_challengehash(challengehash, ntlm, ntlm2_hash, blob, blob_len)) return false; memcpy(ntlm->ntlm2_response, challengehash, 16); ntlm->ntlm2_response_len = ntlm2_response_len; if (!generate_lm2_response(ntlm, ntlm2_hash)) return false; return true; } int ntlm_client_response( const unsigned char **out, size_t *out_len, ntlm_client *ntlm) { unsigned char *domain, *username, *hostname, *ntlm_rep, *session; size_t lm_rep_len, lm_rep_offset, ntlm_rep_len, ntlm_rep_offset, domain_len, domain_offset, username_len, username_offset, hostname_len, hostname_offset, session_len, session_offset; uint32_t flags = 0; bool unicode; NTLM_ASSERT_ARG(out); NTLM_ASSERT_ARG(out_len); NTLM_ASSERT_ARG(ntlm); ENSURE_INITIALIZED(ntlm); *out = NULL; *out_len = 0; if (ntlm->state != NTLM_STATE_RESPONSE) { ntlm_client_set_errmsg(ntlm, "ntlm handle in invalid state"); return -1; } /* * Minimum message size is 64 bytes: * 8 byte signature, * 4 byte message indicator, * 6x8 byte security buffers * 4 byte flags */ ntlm->response.len = 64; unicode = supports_unicode(ntlm) && (ntlm->challenge.flags & NTLM_NEGOTIATE_UNICODE); if (unicode) flags |= NTLM_NEGOTIATE_UNICODE; else flags |= NTLM_NEGOTIATE_OEM; if (unicode) { domain = (unsigned char *)ntlm->userdomain_utf16; domain_len = ntlm->userdomain_utf16_len; username = (unsigned char *)ntlm->username_utf16; username_len = ntlm->username_utf16_len; hostname = (unsigned char *)ntlm->hostname_utf16; hostname_len = ntlm->hostname_utf16_len; } else { domain = (unsigned char *)ntlm->userdomain; domain_len = ntlm->userdomain ? strlen(ntlm->userdomain) : 0; username = (unsigned char *)ntlm->username; username_len = ntlm->username ? strlen(ntlm->username) : 0; hostname = (unsigned char *)ntlm->hostname; hostname_len = ntlm->hostname ? strlen(ntlm->hostname) : 0; } /* Negotiate our requested authentication type with the server's */ if (!(ntlm->flags & NTLM_CLIENT_DISABLE_NTLM2) && (ntlm->challenge.flags & NTLM_NEGOTIATE_NTLM)) { flags |= NTLM_NEGOTIATE_NTLM; if (!generate_ntlm2_response(ntlm)) return -1; } else if ((ntlm->flags & NTLM_CLIENT_ENABLE_NTLM) && (ntlm->challenge.flags & NTLM_NEGOTIATE_NTLM)) { flags |= NTLM_NEGOTIATE_NTLM; if (!generate_ntlm_response(ntlm) || !generate_lm_response(ntlm)) return -1; } else if (ntlm->flags & NTLM_CLIENT_ENABLE_LM) { if (!generate_lm_response(ntlm)) return -1; } else { ntlm_client_set_errmsg(ntlm, "no encryption options could be negotiated"); return -1; } domain_offset = ntlm->response.len; increment_size(&ntlm->response.len, domain_len); username_offset = ntlm->response.len; increment_size(&ntlm->response.len, username_len); hostname_offset = ntlm->response.len; increment_size(&ntlm->response.len, hostname_len); lm_rep_len = ntlm->lm_response_len; lm_rep_offset = ntlm->response.len; increment_size(&ntlm->response.len, lm_rep_len); ntlm_rep = ntlm->ntlm2_response_len ? ntlm->ntlm2_response : ntlm->ntlm_response; ntlm_rep_len = ntlm->ntlm2_response_len ? ntlm->ntlm2_response_len : ntlm->ntlm_response_len; ntlm_rep_offset = ntlm->response.len; increment_size(&ntlm->response.len, ntlm_rep_len); session = NULL; session_len = 0; session_offset = ntlm->response.len; increment_size(&ntlm->response.len, session_len); if (ntlm->response.len == (size_t)-1) { ntlm_client_set_errmsg(ntlm, "message too large"); return -1; } if ((ntlm->response.buf = calloc(1, ntlm->response.len)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return -1; } if (!write_buf(ntlm, &ntlm->response, ntlm_client_signature, sizeof(ntlm_client_signature)) || !write_int32(ntlm, &ntlm->response, 3) || !write_bufinfo(ntlm, &ntlm->response, lm_rep_len, lm_rep_offset) || !write_bufinfo(ntlm, &ntlm->response, ntlm_rep_len, ntlm_rep_offset) || !write_bufinfo(ntlm, &ntlm->response, domain_len, domain_offset) || !write_bufinfo(ntlm, &ntlm->response, username_len, username_offset) || !write_bufinfo(ntlm, &ntlm->response, hostname_len, hostname_offset) || !write_bufinfo(ntlm, &ntlm->response, session_len, session_offset) || !write_int32(ntlm, &ntlm->response, flags) || !write_buf(ntlm, &ntlm->response, domain, domain_len) || !write_buf(ntlm, &ntlm->response, username, username_len) || !write_buf(ntlm, &ntlm->response, hostname, hostname_len) || !write_buf(ntlm, &ntlm->response, ntlm->lm_response, lm_rep_len) || !write_buf(ntlm, &ntlm->response, ntlm_rep, ntlm_rep_len) || !write_buf(ntlm, &ntlm->response, session, session_len)) return -1; NTLM_ASSERT(ntlm, ntlm->response.pos == ntlm->response.len); ntlm->state = NTLM_STATE_COMPLETE; *out = ntlm->response.buf; *out_len = ntlm->response.len; return 0; } void ntlm_client_reset(ntlm_client *ntlm) { if (!ntlm) return; ntlm->state = NTLM_STATE_NEGOTIATE; free_hostname(ntlm); memset(&ntlm->host_version, 0, sizeof(ntlm_version)); reset(ntlm->target); reset(ntlm->target_utf16); ntlm->target_utf16_len = 0; free_credentials(ntlm); ntlm->nonce = 0; ntlm->timestamp = 0; memset(ntlm->lm_response, 0, NTLM_LM_RESPONSE_LEN); ntlm->lm_response_len = 0; memset(ntlm->ntlm_response, 0, NTLM_NTLM_RESPONSE_LEN); ntlm->ntlm_response_len = 0; reset(ntlm->ntlm2_response); ntlm->ntlm2_response_len = 0; reset(ntlm->negotiate.buf); ntlm->negotiate.pos = 0; ntlm->negotiate.len = 0; reset(ntlm->response.buf); ntlm->response.pos = 0; ntlm->response.len = 0; free(ntlm->challenge.target_info); free(ntlm->challenge.target); free(ntlm->challenge.target_domain); free(ntlm->challenge.target_domain_dns); free(ntlm->challenge.target_server); free(ntlm->challenge.target_server_dns); memset(&ntlm->challenge, 0, sizeof(ntlm_challenge)); } void ntlm_client_free(ntlm_client *ntlm) { if (!ntlm) return; ntlm_crypt_shutdown(ntlm); ntlm_unicode_shutdown(ntlm); ntlm_client_reset(ntlm); free(ntlm); }
libgit2-main
deps/ntlmclient/ntlm.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <stdlib.h> #include <stdint.h> #include "ntlm.h" #include "unicode.h" #include "compat.h" typedef unsigned int UTF32; /* at least 32 bits */ typedef unsigned short UTF16; /* at least 16 bits */ typedef unsigned char UTF8; /* typically 8 bits */ /* Some fundamental constants */ #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD #define UNI_MAX_BMP (UTF32)0x0000FFFF #define UNI_MAX_UTF16 (UTF32)0x0010FFFF #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF #define UNI_MAX_UTF8_BYTES_PER_CODE_POINT 4 typedef enum { conversionOK, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ targetExhausted, /* insuff. room in target for conversion */ sourceIllegal /* source sequence is illegal/malformed */ } ConversionResult; typedef enum { strictConversion = 0, lenientConversion } ConversionFlags; static const int halfShift = 10; /* used for shifting by 10 bits */ static const UTF32 halfBase = 0x0010000UL; static const UTF32 halfMask = 0x3FFUL; #define UNI_SUR_HIGH_START (UTF32)0xD800 #define UNI_SUR_HIGH_END (UTF32)0xDBFF #define UNI_SUR_LOW_START (UTF32)0xDC00 #define UNI_SUR_LOW_END (UTF32)0xDFFF #define false 0 #define true 1 /* --------------------------------------------------------------------- */ /* * Index into the table below with the first byte of a UTF-8 sequence to * get the number of trailing bytes that are supposed to follow it. * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is * left as-is for anyone who may want to do such conversion, which was * allowed in earlier algorithms. */ static const char trailingBytesForUTF8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; /* * Magic values subtracted from a buffer value during UTF8 conversion. * This table contains as many values as there might be trailing bytes * in a UTF-8 sequence. */ static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed * into the first byte, depending on how many bytes follow. There are * as many entries in this table as there are UTF-8 sequence types. * (I.e., one byte sequence, two byte... etc.). Remember that sequencs * for *legal* UTF-8 will be 4 or fewer bytes total. */ static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; /* --------------------------------------------------------------------- */ /* The interface converts a whole buffer to avoid function-call overhead. * Constants have been gathered. Loops & conditionals have been removed as * much as possible for efficiency, in favor of drop-through switches. * (See "Note A" at the bottom of the file for equivalent code.) * If your compiler supports it, the "isLegalUTF8" call can be turned * into an inline function. */ static ConversionResult ConvertUTF16toUTF8 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF16* source = *sourceStart; UTF8* target = *targetStart; while (source < sourceEnd) { UTF32 ch; unsigned short bytesToWrite = 0; const UTF32 byteMask = 0xBF; const UTF32 byteMark = 0x80; const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ ch = *source++; /* If we have a surrogate pair, convert to UTF32 first. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { /* If the 16 bits following the high surrogate are in the source buffer... */ if (source < sourceEnd) { UTF32 ch2 = *source; /* If it's a low surrogate, convert to UTF32. */ if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) + halfBase; ++source; } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } else { /* We don't have the 16 bits following the high surrogate. */ --source; /* return to the high surrogate */ result = sourceExhausted; break; } } else if (flags == strictConversion) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } /* Figure out how many bytes the result will require */ if (ch < (UTF32)0x80) { bytesToWrite = 1; } else if (ch < (UTF32)0x800) { bytesToWrite = 2; } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; } else if (ch < (UTF32)0x110000) { bytesToWrite = 4; } else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; } target += bytesToWrite; if (target > targetEnd) { source = oldSource; /* Back up source pointer! */ target -= bytesToWrite; result = targetExhausted; break; } switch (bytesToWrite) { /* note: everything falls through. */ case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]); } target += bytesToWrite; } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ /* * Utility routine to tell whether a sequence of bytes is legal UTF-8. * This must be called with the length pre-determined by the first byte. * If not calling this from ConvertUTF8to*, then the length can be set by: * length = trailingBytesForUTF8[*source]+1; * and the sequence is illegal right away if there aren't that many bytes * available. * If presented with a length > 4, this returns false. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ static inline bool isLegalUTF8(const UTF8 *source, int length) { UTF8 a; const UTF8 *srcptr = source+length; switch (length) { default: return false; /* Everything else falls through when "true"... */ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; case 2: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; switch (*source) { /* no fall-through in this inner switch */ case 0xE0: if (a < 0xA0) return false; break; case 0xED: if (a > 0x9F) return false; break; case 0xF0: if (a < 0x90) return false; break; case 0xF4: if (a > 0x8F) return false; break; default: if (a < 0x80) return false; } case 1: if (*source >= 0x80 && *source < 0xC2) return false; } if (*source > 0xF4) return false; return true; } static ConversionResult ConvertUTF8toUTF16 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF8* source = *sourceStart; UTF16* target = *targetStart; while (source < sourceEnd) { UTF32 ch = 0; unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (extraBytesToRead >= sourceEnd - source) { result = sourceExhausted; break; } /* Do this check whether lenient or strict */ if (!isLegalUTF8(source, extraBytesToRead+1)) { result = sourceIllegal; break; } /* * The cases all fall through. See "Note A" below. */ switch (extraBytesToRead) { case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; if (target >= targetEnd) { source -= (extraBytesToRead+1); /* Back up source pointer! */ result = targetExhausted; break; } if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { source -= (extraBytesToRead+1); /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = (UTF16)ch; /* normal case */ } } else if (ch > UNI_MAX_UTF16) { if (flags == strictConversion) { result = sourceIllegal; source -= (extraBytesToRead+1); /* return to the start */ break; /* Bail out; shouldn't continue */ } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { /* target is a character in range 0xFFFF - 0x10FFFF. */ if (target + 1 >= targetEnd) { source -= (extraBytesToRead+1); /* Back up source pointer! */ result = targetExhausted; break; } ch -= halfBase; *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); } } *sourceStart = source; *targetStart = target; return result; } bool ntlm_unicode_init(ntlm_client *ntlm) { NTLM_UNUSED(ntlm); return true; } typedef enum { unicode_builtin_utf8_to_16, unicode_builtin_utf16_to_8 } unicode_builtin_encoding_direction; static inline bool unicode_builtin_encoding_convert( char **converted, size_t *converted_len, ntlm_client *ntlm, const char *string, size_t string_len, unicode_builtin_encoding_direction direction) { const char *in_start, *in_end; char *out, *out_start, *out_end, *new_out; size_t out_size, out_len; bool success = false; ConversionResult result; *converted = NULL; *converted_len = 0; in_start = string; in_end = in_start + string_len; /* * When translating UTF8 to UTF16, these strings are only used * internally, and we obey the given length, so we can simply * use a buffer that is 2x the size. Add an extra byte to NUL * terminate the results (two bytes for UTF16). */ if (direction == unicode_builtin_utf8_to_16) out_size = (string_len * 2 + 2); else out_size = (string_len / 2 + 1); /* Round to the nearest multiple of 8 */ out_size = (out_size + 7) & ~7; if ((out = malloc(out_size)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return false; } out_start = out; out_end = out_start + out_size; /* Make room for NUL termination */ if (direction == unicode_builtin_utf16_to_8) out_end--; while (true) { if (direction == unicode_builtin_utf8_to_16) result = ConvertUTF8toUTF16( (const UTF8 **)&in_start, (UTF8 *)in_end, (UTF16 **)&out_start, (UTF16 *)out_end, strictConversion); else result = ConvertUTF16toUTF8( (const UTF16 **)&in_start, (UTF16 *)in_end, (UTF8 **)&out_start, (UTF8 *)out_end, lenientConversion); switch (result) { case conversionOK: success = true; goto done; case sourceExhausted: ntlm_client_set_errmsg(ntlm, "invalid unicode string; trailing data remains"); goto done; case targetExhausted: break; case sourceIllegal: ntlm_client_set_errmsg(ntlm, "invalid unicode string; trailing data remains"); goto done; default: ntlm_client_set_errmsg(ntlm, "unknown unicode conversion failure"); goto done; } /* Grow buffer size by 1.5 (rounded up to a multiple of 8) */ out_size = ((((out_size << 1) - (out_size >> 1)) + 7) & ~7); if (out_size > NTLM_UNICODE_MAX_LEN) { ntlm_client_set_errmsg(ntlm, "unicode conversion too large"); goto done; } if ((new_out = realloc(out, out_size)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); goto done; } out_len = out_start - out; out = new_out; out_start = new_out + out_len; out_end = out + out_size; /* Make room for NUL termination */ out_end -= (direction == unicode_builtin_utf8_to_16) ? 2 : 1; } done: if (!success) { free(out); return false; } out_len = (out_start - out); /* NUL terminate */ out[out_len] = '\0'; if (direction == unicode_builtin_utf8_to_16) out[out_len+1] = '\0'; *converted = out; *converted_len = out_len; return true; } bool ntlm_unicode_utf8_to_16( char **converted, size_t *converted_len, ntlm_client *client, const char *string, size_t string_len) { return unicode_builtin_encoding_convert(converted, converted_len, client, string, string_len, unicode_builtin_utf8_to_16); } bool ntlm_unicode_utf16_to_8( char **converted, size_t *converted_len, ntlm_client *client, const char *string, size_t string_len) { return unicode_builtin_encoding_convert(converted, converted_len, client, string, string_len, unicode_builtin_utf16_to_8); } void ntlm_unicode_shutdown(ntlm_client *ntlm) { NTLM_UNUSED(ntlm); }
libgit2-main
deps/ntlmclient/unicode_builtin.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <stdlib.h> #include <stdint.h> #include <arpa/inet.h> #include "compat.h" #include "util.h" void ntlm_memzero(void *data, size_t size) { volatile uint8_t *scan = (volatile uint8_t *)data; while (size--) *scan++ = 0x0; } uint64_t ntlm_htonll(uint64_t value) { static union { uint32_t i; char c[8]; } test = { 0x01020304 }; if (test.c[0] == 0x01) return value; else return ((uint64_t)htonl(value) << 32) | htonl((uint64_t)value >> 32); }
libgit2-main
deps/ntlmclient/util.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <stdlib.h> #include <string.h> #ifdef CRYPT_OPENSSL_DYNAMIC # include <dlfcn.h> #else # include <openssl/rand.h> # include <openssl/des.h> # include <openssl/md4.h> # include <openssl/hmac.h> # include <openssl/err.h> #endif #include "ntlm.h" #include "compat.h" #include "util.h" #include "crypt.h" #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(CRYPT_OPENSSL_DYNAMIC) static inline HMAC_CTX *HMAC_CTX_new(void) { return calloc(1, sizeof(HMAC_CTX)); } static inline int HMAC_CTX_reset(HMAC_CTX *ctx) { ntlm_memzero(ctx, sizeof(HMAC_CTX)); return 1; } static inline void HMAC_CTX_free(HMAC_CTX *ctx) { free(ctx); } #endif #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)) || \ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x03050000fL) || \ defined(CRYPT_OPENSSL_DYNAMIC) static inline void HMAC_CTX_cleanup(HMAC_CTX *ctx) { NTLM_UNUSED(ctx); } #endif #ifdef CRYPT_OPENSSL_DYNAMIC static bool ntlm_crypt_init_functions(ntlm_client *ntlm) { void *handle; if ((handle = dlopen("libssl.so.1.1", RTLD_NOW)) == NULL && (handle = dlopen("libssl.1.1.dylib", RTLD_NOW)) == NULL && (handle = dlopen("libssl.so.1.0.0", RTLD_NOW)) == NULL && (handle = dlopen("libssl.1.0.0.dylib", RTLD_NOW)) == NULL && (handle = dlopen("libssl.so.10", RTLD_NOW)) == NULL) { ntlm_client_set_errmsg(ntlm, "could not open libssl"); return false; } ntlm->crypt_ctx.des_set_key_fn = dlsym(handle, "DES_set_key"); ntlm->crypt_ctx.des_ecb_encrypt_fn = dlsym(handle, "DES_ecb_encrypt"); ntlm->crypt_ctx.err_get_error_fn = dlsym(handle, "ERR_get_error"); ntlm->crypt_ctx.err_lib_error_string_fn = dlsym(handle, "ERR_lib_error_string"); ntlm->crypt_ctx.evp_md5_fn = dlsym(handle, "EVP_md5"); ntlm->crypt_ctx.hmac_ctx_new_fn = dlsym(handle, "HMAC_CTX_new"); ntlm->crypt_ctx.hmac_ctx_free_fn = dlsym(handle, "HMAC_CTX_free"); ntlm->crypt_ctx.hmac_ctx_reset_fn = dlsym(handle, "HMAC_CTX_reset"); ntlm->crypt_ctx.hmac_init_ex_fn = dlsym(handle, "HMAC_Init_ex"); ntlm->crypt_ctx.hmac_update_fn = dlsym(handle, "HMAC_Update"); ntlm->crypt_ctx.hmac_final_fn = dlsym(handle, "HMAC_Final"); ntlm->crypt_ctx.md4_fn = dlsym(handle, "MD4"); ntlm->crypt_ctx.rand_bytes_fn = dlsym(handle, "RAND_bytes"); if (!ntlm->crypt_ctx.des_set_key_fn || !ntlm->crypt_ctx.des_ecb_encrypt_fn || !ntlm->crypt_ctx.err_get_error_fn || !ntlm->crypt_ctx.err_lib_error_string_fn || !ntlm->crypt_ctx.evp_md5_fn || !ntlm->crypt_ctx.hmac_init_ex_fn || !ntlm->crypt_ctx.hmac_update_fn || !ntlm->crypt_ctx.hmac_final_fn || !ntlm->crypt_ctx.md4_fn || !ntlm->crypt_ctx.rand_bytes_fn) { ntlm_client_set_errmsg(ntlm, "could not load libssl functions"); dlclose(handle); return false; } /* Toggle legacy HMAC context functions */ if (ntlm->crypt_ctx.hmac_ctx_new_fn && ntlm->crypt_ctx.hmac_ctx_free_fn && ntlm->crypt_ctx.hmac_ctx_reset_fn) { ntlm->crypt_ctx.hmac_ctx_cleanup_fn = HMAC_CTX_cleanup; } else { ntlm->crypt_ctx.hmac_ctx_cleanup_fn = dlsym(handle, "HMAC_CTX_cleanup"); if (!ntlm->crypt_ctx.hmac_ctx_cleanup_fn) { ntlm_client_set_errmsg(ntlm, "could not load legacy libssl functions"); dlclose(handle); return false; } ntlm->crypt_ctx.hmac_ctx_new_fn = HMAC_CTX_new; ntlm->crypt_ctx.hmac_ctx_free_fn = HMAC_CTX_free; ntlm->crypt_ctx.hmac_ctx_reset_fn = HMAC_CTX_reset; } ntlm->crypt_ctx.openssl_handle = handle; return true; } #else /* CRYPT_OPENSSL_DYNAMIC */ static bool ntlm_crypt_init_functions(ntlm_client *ntlm) { ntlm->crypt_ctx.des_set_key_fn = DES_set_key; ntlm->crypt_ctx.des_ecb_encrypt_fn = DES_ecb_encrypt; ntlm->crypt_ctx.err_get_error_fn = ERR_get_error; ntlm->crypt_ctx.err_lib_error_string_fn = ERR_lib_error_string; ntlm->crypt_ctx.evp_md5_fn = EVP_md5; ntlm->crypt_ctx.hmac_ctx_new_fn = HMAC_CTX_new; ntlm->crypt_ctx.hmac_ctx_free_fn = HMAC_CTX_free; ntlm->crypt_ctx.hmac_ctx_reset_fn = HMAC_CTX_reset; ntlm->crypt_ctx.hmac_ctx_cleanup_fn = HMAC_CTX_cleanup; ntlm->crypt_ctx.hmac_init_ex_fn = HMAC_Init_ex; ntlm->crypt_ctx.hmac_update_fn = HMAC_Update; ntlm->crypt_ctx.hmac_final_fn = HMAC_Final; ntlm->crypt_ctx.md4_fn = MD4; ntlm->crypt_ctx.rand_bytes_fn = RAND_bytes; return true; } #endif /* CRYPT_OPENSSL_DYNAMIC */ bool ntlm_crypt_init(ntlm_client *ntlm) { if (!ntlm_crypt_init_functions(ntlm)) return false; ntlm->crypt_ctx.hmac = ntlm->crypt_ctx.hmac_ctx_new_fn(); if (ntlm->crypt_ctx.hmac == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return false; } return true; } bool ntlm_random_bytes( unsigned char *out, ntlm_client *ntlm, size_t len) { int rc = ntlm->crypt_ctx.rand_bytes_fn(out, len); if (rc != 1) { ntlm_client_set_errmsg(ntlm, ntlm->crypt_ctx.err_lib_error_string_fn(ntlm->crypt_ctx.err_get_error_fn())); return false; } return true; } bool ntlm_des_encrypt( ntlm_des_block *out, ntlm_client *ntlm, ntlm_des_block *plaintext, ntlm_des_block *key) { DES_key_schedule keysched; NTLM_UNUSED(ntlm); memset(out, 0, sizeof(ntlm_des_block)); ntlm->crypt_ctx.des_set_key_fn(key, &keysched); ntlm->crypt_ctx.des_ecb_encrypt_fn(plaintext, out, &keysched, DES_ENCRYPT); return true; } bool ntlm_md4_digest( unsigned char out[CRYPT_MD4_DIGESTSIZE], ntlm_client *ntlm, const unsigned char *in, size_t in_len) { ntlm->crypt_ctx.md4_fn(in, in_len, out); return true; } bool ntlm_hmac_md5_init( ntlm_client *ntlm, const unsigned char *key, size_t key_len) { const EVP_MD *md5 = ntlm->crypt_ctx.evp_md5_fn(); ntlm->crypt_ctx.hmac_ctx_cleanup_fn(ntlm->crypt_ctx.hmac); return ntlm->crypt_ctx.hmac_ctx_reset_fn(ntlm->crypt_ctx.hmac) && ntlm->crypt_ctx.hmac_init_ex_fn(ntlm->crypt_ctx.hmac, key, key_len, md5, NULL); } bool ntlm_hmac_md5_update( ntlm_client *ntlm, const unsigned char *in, size_t in_len) { return ntlm->crypt_ctx.hmac_update_fn(ntlm->crypt_ctx.hmac, in, in_len); } bool ntlm_hmac_md5_final( unsigned char *out, size_t *out_len, ntlm_client *ntlm) { unsigned int len; if (*out_len < CRYPT_MD5_DIGESTSIZE) return false; if (!ntlm->crypt_ctx.hmac_final_fn(ntlm->crypt_ctx.hmac, out, &len)) return false; *out_len = len; return true; } void ntlm_crypt_shutdown(ntlm_client *ntlm) { if (ntlm->crypt_ctx.hmac) { ntlm->crypt_ctx.hmac_ctx_cleanup_fn(ntlm->crypt_ctx.hmac); ntlm->crypt_ctx.hmac_ctx_free_fn(ntlm->crypt_ctx.hmac); } #ifdef CRYPT_OPENSSL_DYNAMIC if (ntlm->crypt_ctx.openssl_handle) dlclose(ntlm->crypt_ctx.openssl_handle); #endif memset(&ntlm->crypt_ctx, 0, sizeof(ntlm_crypt_ctx)); }
libgit2-main
deps/ntlmclient/crypt_openssl.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <stdlib.h> #include <string.h> #include "mbedtls/ctr_drbg.h" #include "mbedtls/des.h" #include "mbedtls/entropy.h" #include "mbedtls/md4.h" #include "ntlm.h" #include "crypt.h" bool ntlm_crypt_init(ntlm_client *ntlm) { const mbedtls_md_info_t *info = mbedtls_md_info_from_type(MBEDTLS_MD_MD5); mbedtls_md_init(&ntlm->crypt_ctx.hmac); if (mbedtls_md_setup(&ntlm->crypt_ctx.hmac, info, 1) != 0) { ntlm_client_set_errmsg(ntlm, "could not setup mbedtls digest"); return false; } return true; } bool ntlm_random_bytes( unsigned char *out, ntlm_client *ntlm, size_t len) { mbedtls_ctr_drbg_context ctr_drbg; mbedtls_entropy_context entropy; bool ret = true; const unsigned char personalization[] = { 0xec, 0xb5, 0xd1, 0x0b, 0x8f, 0x15, 0x1f, 0xc2, 0xe4, 0x8e, 0xec, 0x36, 0xf7, 0x0a, 0x45, 0x9a, 0x1f, 0xe1, 0x35, 0x58, 0xb1, 0xcb, 0xfd, 0x8a, 0x57, 0x5c, 0x75, 0x7d, 0x2f, 0xc9, 0x70, 0xac }; mbedtls_ctr_drbg_init(&ctr_drbg); mbedtls_entropy_init(&entropy); if (mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, personalization, sizeof(personalization)) || mbedtls_ctr_drbg_random(&ctr_drbg, out, len)) { ntlm_client_set_errmsg(ntlm, "random generation failed"); ret = false; } mbedtls_entropy_free(&entropy); mbedtls_ctr_drbg_free(&ctr_drbg); return ret; } bool ntlm_des_encrypt( ntlm_des_block *out, ntlm_client *ntlm, ntlm_des_block *plaintext, ntlm_des_block *key) { mbedtls_des_context ctx; bool success = false; mbedtls_des_init(&ctx); if (mbedtls_des_setkey_enc(&ctx, *key) || mbedtls_des_crypt_ecb(&ctx, *plaintext, *out)) { ntlm_client_set_errmsg(ntlm, "DES encryption failed"); goto done; } success = true; done: mbedtls_des_free(&ctx); return success; } bool ntlm_md4_digest( unsigned char out[CRYPT_MD4_DIGESTSIZE], ntlm_client *ntlm, const unsigned char *in, size_t in_len) { mbedtls_md4_context ctx; NTLM_UNUSED(ntlm); mbedtls_md4_init(&ctx); mbedtls_md4_starts(&ctx); mbedtls_md4_update(&ctx, in, in_len); mbedtls_md4_finish(&ctx, out); mbedtls_md4_free(&ctx); return true; } bool ntlm_hmac_md5_init( ntlm_client *ntlm, const unsigned char *key, size_t key_len) { if (ntlm->crypt_ctx.hmac_initialized) { if (mbedtls_md_hmac_reset(&ntlm->crypt_ctx.hmac)) return false; } ntlm->crypt_ctx.hmac_initialized = !mbedtls_md_hmac_starts(&ntlm->crypt_ctx.hmac, key, key_len); return ntlm->crypt_ctx.hmac_initialized; } bool ntlm_hmac_md5_update( ntlm_client *ntlm, const unsigned char *in, size_t in_len) { return !mbedtls_md_hmac_update(&ntlm->crypt_ctx.hmac, in, in_len); } bool ntlm_hmac_md5_final( unsigned char *out, size_t *out_len, ntlm_client *ntlm) { if (*out_len < CRYPT_MD5_DIGESTSIZE) return false; return !mbedtls_md_hmac_finish(&ntlm->crypt_ctx.hmac, out); } void ntlm_crypt_shutdown(ntlm_client *ntlm) { mbedtls_md_free(&ntlm->crypt_ctx.hmac); }
libgit2-main
deps/ntlmclient/crypt_mbedtls.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <locale.h> #include <iconv.h> #include <string.h> #include <errno.h> #include "ntlmclient.h" #include "unicode.h" #include "ntlm.h" #include "compat.h" typedef enum { unicode_iconv_utf8_to_16, unicode_iconv_utf16_to_8 } unicode_iconv_encoding_direction; bool ntlm_unicode_init(ntlm_client *ntlm) { ntlm->unicode_ctx.utf8_to_16 = iconv_open("UTF-16LE", "UTF-8"); ntlm->unicode_ctx.utf16_to_8 = iconv_open("UTF-8", "UTF-16LE"); if (ntlm->unicode_ctx.utf8_to_16 == (iconv_t)-1 || ntlm->unicode_ctx.utf16_to_8 == (iconv_t)-1) { if (errno == EINVAL) ntlm_client_set_errmsg(ntlm, "iconv does not support UTF8 <-> UTF16 conversion"); else ntlm_client_set_errmsg(ntlm, strerror(errno)); return false; } return true; } static inline bool unicode_iconv_encoding_convert( char **converted, size_t *converted_len, ntlm_client *ntlm, const char *string, size_t string_len, unicode_iconv_encoding_direction direction) { char *in_start, *out_start, *out, *new_out; size_t in_start_len, out_start_len, out_size, nul_size, ret, written = 0; iconv_t converter; *converted = NULL; *converted_len = 0; /* * When translating UTF8 to UTF16, these strings are only used * internally, and we obey the given length, so we can simply * use a buffer that is 2x the size. When translating from UTF16 * to UTF8, we may need to return to callers, so we need to NUL * terminate and expect an extra byte for UTF8, two for UTF16. */ if (direction == unicode_iconv_utf8_to_16) { converter = ntlm->unicode_ctx.utf8_to_16; out_size = (string_len * 2) + 2; nul_size = 2; } else { converter = ntlm->unicode_ctx.utf16_to_8; out_size = (string_len / 2) + 1; nul_size = 1; } /* Round to the nearest multiple of 8 */ out_size = (out_size + 7) & ~7; if ((out = malloc(out_size)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); return false; } in_start = (char *)string; in_start_len = string_len; while (true) { out_start = out + written; out_start_len = (out_size - nul_size) - written; ret = iconv(converter, &in_start, &in_start_len, &out_start, &out_start_len); written = (out_size - nul_size) - out_start_len; if (ret == 0) break; if (ret == (size_t)-1 && errno != E2BIG) { ntlm_client_set_errmsg(ntlm, strerror(errno)); goto on_error; } /* Grow buffer size by 1.5 (rounded up to a multiple of 8) */ out_size = ((((out_size << 1) - (out_size >> 1)) + 7) & ~7); if (out_size > NTLM_UNICODE_MAX_LEN) { ntlm_client_set_errmsg(ntlm, "unicode conversion too large"); goto on_error; } if ((new_out = realloc(out, out_size)) == NULL) { ntlm_client_set_errmsg(ntlm, "out of memory"); goto on_error; } out = new_out; } if (in_start_len != 0) { ntlm_client_set_errmsg(ntlm, "invalid unicode string; trailing data remains"); goto on_error; } /* NUL terminate */ out[written] = '\0'; if (direction == unicode_iconv_utf8_to_16) out[written + 1] = '\0'; *converted = out; if (converted_len) *converted_len = written; return true; on_error: free(out); return false; } bool ntlm_unicode_utf8_to_16( char **converted, size_t *converted_len, ntlm_client *ntlm, const char *string, size_t string_len) { return unicode_iconv_encoding_convert( converted, converted_len, ntlm, string, string_len, unicode_iconv_utf8_to_16); } bool ntlm_unicode_utf16_to_8( char **converted, size_t *converted_len, ntlm_client *ntlm, const char *string, size_t string_len) { return unicode_iconv_encoding_convert( converted, converted_len, ntlm, string, string_len, unicode_iconv_utf16_to_8); } void ntlm_unicode_shutdown(ntlm_client *ntlm) { if (ntlm->unicode_ctx.utf16_to_8 != (iconv_t)0 && ntlm->unicode_ctx.utf16_to_8 != (iconv_t)-1) iconv_close(ntlm->unicode_ctx.utf16_to_8); if (ntlm->unicode_ctx.utf8_to_16 != (iconv_t)0 && ntlm->unicode_ctx.utf8_to_16 != (iconv_t)-1) iconv_close(ntlm->unicode_ctx.utf8_to_16); ntlm->unicode_ctx.utf8_to_16 = (iconv_t)-1; ntlm->unicode_ctx.utf16_to_8 = (iconv_t)-1; }
libgit2-main
deps/ntlmclient/unicode_iconv.c
/* * Copyright (c) Edward Thomson. All rights reserved. * * This file is part of ntlmclient, distributed under the MIT license. * For full terms and copyright information, and for third-party * copyright information, see the included LICENSE.txt file. */ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <CommonCrypto/CommonCrypto.h> #include "ntlm.h" #include "crypt.h" bool ntlm_crypt_init(ntlm_client *ntlm) { memset(&ntlm->crypt_ctx, 0, sizeof(ntlm_crypt_ctx)); return true; } bool ntlm_random_bytes( unsigned char *out, ntlm_client *ntlm, size_t len) { int fd, ret; size_t total = 0; if ((fd = open("/dev/urandom", O_RDONLY)) < 0) { ntlm_client_set_errmsg(ntlm, strerror(errno)); return false; } while (total < len) { if ((ret = read(fd, out, (len - total))) < 0) { ntlm_client_set_errmsg(ntlm, strerror(errno)); return false; } else if (ret == 0) { ntlm_client_set_errmsg(ntlm, "unexpected eof on random device"); return false; } total += ret; } close(fd); return true; } bool ntlm_des_encrypt( ntlm_des_block *out, ntlm_client *ntlm, ntlm_des_block *plaintext, ntlm_des_block *key) { size_t written; NTLM_UNUSED(ntlm); CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key, sizeof(ntlm_des_block), NULL, plaintext, sizeof(ntlm_des_block), out, sizeof(ntlm_des_block), &written); return (result == kCCSuccess) ? true : false; } bool ntlm_md4_digest( unsigned char out[CRYPT_MD4_DIGESTSIZE], ntlm_client *ntlm, const unsigned char *in, size_t in_len) { NTLM_UNUSED(ntlm); return !!CC_MD4(in, in_len, out); } bool ntlm_hmac_md5_init( ntlm_client *ntlm, const unsigned char *key, size_t key_len) { CCHmacInit(&ntlm->crypt_ctx.hmac, kCCHmacAlgMD5, key, key_len); return true; } bool ntlm_hmac_md5_update( ntlm_client *ntlm, const unsigned char *data, size_t data_len) { CCHmacUpdate(&ntlm->crypt_ctx.hmac, data, data_len); return true; } bool ntlm_hmac_md5_final( unsigned char *out, size_t *out_len, ntlm_client *ntlm) { if (*out_len < CRYPT_MD5_DIGESTSIZE) return false; CCHmacFinal(&ntlm->crypt_ctx.hmac, out); *out_len = CRYPT_MD5_DIGESTSIZE; return true; } void ntlm_crypt_shutdown(ntlm_client *ntlm) { NTLM_UNUSED(ntlm); }
libgit2-main
deps/ntlmclient/crypt_commoncrypto.c
/* inflate.c -- zlib decompression * Copyright (C) 1995-2022 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * Change history: * * 1.2.beta0 24 Nov 2002 * - First version -- complete rewrite of inflate to simplify code, avoid * creation of window when not needed, minimize use of window when it is * needed, make inffast.c even faster, implement gzip decoding, and to * improve code readability and style over the previous zlib inflate code * * 1.2.beta1 25 Nov 2002 * - Use pointers for available input and output checking in inffast.c * - Remove input and output counters in inffast.c * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 * - Remove unnecessary second byte pull from length extra in inffast.c * - Unroll direct copy to three copies per loop in inffast.c * * 1.2.beta2 4 Dec 2002 * - Change external routine names to reduce potential conflicts * - Correct filename to inffixed.h for fixed tables in inflate.c * - Make hbuf[] unsigned char to match parameter type in inflate.c * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) * to avoid negation problem on Alphas (64 bit) in inflate.c * * 1.2.beta3 22 Dec 2002 * - Add comments on state->bits assertion in inffast.c * - Add comments on op field in inftrees.h * - Fix bug in reuse of allocated window after inflateReset() * - Remove bit fields--back to byte structure for speed * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths * - Change post-increments to pre-increments in inflate_fast(), PPC biased? * - Add compile time option, POSTINC, to use post-increments instead (Intel?) * - Make MATCH copy in inflate() much faster for when inflate_fast() not used * - Use local copies of stream next and avail values, as well as local bit * buffer and bit count in inflate()--for speed when inflate_fast() not used * * 1.2.beta4 1 Jan 2003 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings * - Move a comment on output buffer sizes from inffast.c to inflate.c * - Add comments in inffast.c to introduce the inflate_fast() routine * - Rearrange window copies in inflate_fast() for speed and simplification * - Unroll last copy for window match in inflate_fast() * - Use local copies of window variables in inflate_fast() for speed * - Pull out common wnext == 0 case for speed in inflate_fast() * - Make op and len in inflate_fast() unsigned for consistency * - Add FAR to lcode and dcode declarations in inflate_fast() * - Simplified bad distance check in inflate_fast() * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new * source file infback.c to provide a call-back interface to inflate for * programs like gzip and unzip -- uses window as output buffer to avoid * window copying * * 1.2.beta5 1 Jan 2003 * - Improved inflateBack() interface to allow the caller to provide initial * input in strm. * - Fixed stored blocks bug in inflateBack() * * 1.2.beta6 4 Jan 2003 * - Added comments in inffast.c on effectiveness of POSTINC * - Typecasting all around to reduce compiler warnings * - Changed loops from while (1) or do {} while (1) to for (;;), again to * make compilers happy * - Changed type of window in inflateBackInit() to unsigned char * * * 1.2.beta7 27 Jan 2003 * - Changed many types to unsigned or unsigned short to avoid warnings * - Added inflateCopy() function * * 1.2.0 9 Mar 2003 * - Changed inflateBack() interface to provide separate opaque descriptors * for the in() and out() functions * - Changed inflateBack() argument and in_func typedef to swap the length * and buffer address return values for the input function * - Check next_in and next_out for Z_NULL on entry to inflate() * * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifdef MAKEFIXED # ifndef BUILDFIXED # define BUILDFIXED # endif #endif /* function prototypes */ local int inflateStateCheck OF((z_streamp strm)); local void fixedtables OF((struct inflate_state FAR *state)); local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, unsigned copy)); #ifdef BUILDFIXED void makefixed OF((void)); #endif local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, unsigned len)); local int inflateStateCheck(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) return 1; state = (struct inflate_state FAR *)strm->state; if (state == Z_NULL || state->strm != strm || state->mode < HEAD || state->mode > SYNC) return 1; return 0; } int ZEXPORT inflateResetKeep(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; strm->total_in = strm->total_out = state->total = 0; strm->msg = Z_NULL; if (state->wrap) /* to support ill-conceived Java test suite */ strm->adler = state->wrap & 1; state->mode = HEAD; state->last = 0; state->havedict = 0; state->flags = -1; state->dmax = 32768U; state->head = Z_NULL; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; state->sane = 1; state->back = -1; Tracev((stderr, "inflate: reset\n")); return Z_OK; } int ZEXPORT inflateReset(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; state->wsize = 0; state->whave = 0; state->wnext = 0; return inflateResetKeep(strm); } int ZEXPORT inflateReset2(strm, windowBits) z_streamp strm; int windowBits; { int wrap; struct inflate_state FAR *state; /* get the state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 5; #ifdef GUNZIP if (windowBits < 48) windowBits &= 15; #endif } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) return Z_STREAM_ERROR; if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { ZFREE(strm, state->window); state->window = Z_NULL; } /* update state and reset the rest of it */ state->wrap = wrap; state->wbits = (unsigned)windowBits; return inflateReset(strm); } int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) z_streamp strm; int windowBits; const char *version; int stream_size; { int ret; struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; #endif } if (strm->zfree == (free_func)0) #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zfree = zcfree; #endif state = (struct inflate_state FAR *) ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->strm = strm; state->window = Z_NULL; state->mode = HEAD; /* to pass state test in inflateReset2() */ ret = inflateReset2(strm, windowBits); if (ret != Z_OK) { ZFREE(strm, state); strm->state = Z_NULL; } return ret; } int ZEXPORT inflateInit_(strm, version, stream_size) z_streamp strm; const char *version; int stream_size; { return inflateInit2_(strm, DEF_WBITS, version, stream_size); } int ZEXPORT inflatePrime(strm, bits, value) z_streamp strm; int bits; int value; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (bits < 0) { state->hold = 0; state->bits = 0; return Z_OK; } if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; value &= (1L << bits) - 1; state->hold += (unsigned)value << state->bits; state->bits += (uInt)bits; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } #ifdef MAKEFIXED #include <stdio.h> /* Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also defines BUILDFIXED, so the tables are built on the fly. makefixed() writes those tables to stdout, which would be piped to inffixed.h. A small program can simply call makefixed to do this: void makefixed(void); int main(void) { makefixed(); return 0; } Then that can be linked with zlib built with MAKEFIXED defined and run: a.out > inffixed.h */ void makefixed() { unsigned low, size; struct inflate_state state; fixedtables(&state); puts(" /* inffixed.h -- table for decoding fixed codes"); puts(" * Generated automatically by makefixed()."); puts(" */"); puts(""); puts(" /* WARNING: this file should *not* be used by applications."); puts(" It is part of the implementation of this library and is"); puts(" subject to change. Applications should only use zlib.h."); puts(" */"); puts(""); size = 1U << 9; printf(" static const code lenfix[%u] = {", size); low = 0; for (;;) { if ((low % 7) == 0) printf("\n "); printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, state.lencode[low].bits, state.lencode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); size = 1U << 5; printf("\n static const code distfix[%u] = {", size); low = 0; for (;;) { if ((low % 6) == 0) printf("\n "); printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, state.distcode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); } #endif /* MAKEFIXED */ /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ local int updatewindow(strm, end, copy) z_streamp strm; const Bytef *end; unsigned copy; { struct inflate_state FAR *state; unsigned dist; state = (struct inflate_state FAR *)strm->state; /* if it hasn't been done already, allocate space for the window */ if (state->window == Z_NULL) { state->window = (unsigned char FAR *) ZALLOC(strm, 1U << state->wbits, sizeof(unsigned char)); if (state->window == Z_NULL) return 1; } /* if window not in use yet, initialize */ if (state->wsize == 0) { state->wsize = 1U << state->wbits; state->wnext = 0; state->whave = 0; } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state->wsize) { zmemcpy(state->window, end - state->wsize, state->wsize); state->wnext = 0; state->whave = state->wsize; } else { dist = state->wsize - state->wnext; if (dist > copy) dist = copy; zmemcpy(state->window + state->wnext, end - copy, dist); copy -= dist; if (copy) { zmemcpy(state->window, end - copy, copy); state->wnext = copy; state->whave = state->wsize; } else { state->wnext += dist; if (state->wnext == state->wsize) state->wnext = 0; if (state->whave < state->wsize) state->whave += dist; } } return 0; } /* Macros for inflate(): */ /* check function to use adler32() for zlib or crc32() for gzip */ #ifdef GUNZIP # define UPDATE_CHECK(check, buf, len) \ (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) #else # define UPDATE_CHECK(check, buf, len) adler32(check, buf, len) #endif /* check macros for header crc */ #ifdef GUNZIP # define CRC2(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ check = crc32(check, hbuf, 2); \ } while (0) # define CRC4(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ hbuf[2] = (unsigned char)((word) >> 16); \ hbuf[3] = (unsigned char)((word) >> 24); \ check = crc32(check, hbuf, 4); \ } while (0) #endif /* Load registers with state in inflate() for speed */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Restore state from registers in inflate() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflate() if there is no input available. */ #define PULLBYTE() \ do { \ if (have == 0) goto inf_leave; \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflate(). */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* inflate() uses a state machine to process as much input data and generate as much output data as possible before returning. The state machine is structured roughly as follows: for (;;) switch (state) { ... case STATEn: if (not enough input data or output space to make progress) return; ... make progress ... state = STATEm; break; ... } so when inflate() is called again, the same case is attempted again, and if the appropriate resources are provided, the machine proceeds to the next state. The NEEDBITS() macro is usually the way the state evaluates whether it can proceed or should return. NEEDBITS() does the return if the requested bits are not available. The typical use of the BITS macros is: NEEDBITS(n); ... do something with BITS(n) ... DROPBITS(n); where NEEDBITS(n) either returns from inflate() if there isn't enough input left to load n bits into the accumulator, or it continues. BITS(n) gives the low n bits in the accumulator. When done, DROPBITS(n) drops the low n bits off the accumulator. INITBITS() clears the accumulator and sets the number of available bits to zero. BYTEBITS() discards just enough bits to put the accumulator on a byte boundary. After BYTEBITS() and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return if there is no input available. The decoding of variable length codes uses PULLBYTE() directly in order to pull just enough bytes to decode the next code, and no more. Some states loop until they get enough input, making sure that enough state information is maintained to continue the loop where it left off if NEEDBITS() returns in the loop. For example, want, need, and keep would all have to actually be part of the saved state in case NEEDBITS() returns: case STATEw: while (want < need) { NEEDBITS(n); keep[want++] = BITS(n); DROPBITS(n); } state = STATEx; case STATEx: As shown above, if the next state is also the next case, then the break is omitted. A state may also return if there is not enough output space available to complete that state. Those states are copying stored data, writing a literal byte, and copying a matching string. When returning, a "goto inf_leave" is used to update the total counters, update the check value, and determine whether any progress has been made during that inflate() call in order to return the proper return code. Progress is defined as a change in either strm->avail_in or strm->avail_out. When there is a window, goto inf_leave will update the window with the last output written. If a goto inf_leave occurs in the middle of decompression and there is no window currently, goto inf_leave will create one and copy output to the window for the next call of inflate(). In this implementation, the flush parameter of inflate() only affects the return code (per zlib.h). inflate() always writes as much as possible to strm->next_out, given the space available and the provided input--the effect documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers the allocation of and copying into a sliding window until necessary, which provides the effect documented in zlib.h for Z_FINISH when the entire input stream available. So the only thing the flush parameter actually does is: when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it will return Z_BUF_ERROR if it has not reached the end of the stream. */ int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; z_const unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned in, out; /* save starting available input and output */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (inflateStateCheck(strm) || strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ if (state->wbits == 0) state->wbits = 15; state->check = crc32(0L, Z_NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } if (state->head != Z_NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (state->wbits == 0) state->wbits = len; if (len > 15 || len > state->wbits) { strm->msg = (char *)"invalid window size"; state->mode = BAD; break; } state->dmax = 1U << len; state->flags = 0; /* indicate zlib header */ Tracev((stderr, "inflate: zlib header ok\n")); strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } if (state->flags & 0xe000) { strm->msg = (char *)"unknown header flags set"; state->mode = BAD; break; } if (state->head != Z_NULL) state->head->text = (int)((hold >> 8) & 1); if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = TIME; /* fallthrough */ case TIME: NEEDBITS(32); if (state->head != Z_NULL) state->head->time = hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC4(state->check, hold); INITBITS(); state->mode = OS; /* fallthrough */ case OS: NEEDBITS(16); if (state->head != Z_NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; /* fallthrough */ case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (unsigned)(hold); if (state->head != Z_NULL) state->head->extra_len = (unsigned)hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); } else if (state->head != Z_NULL) state->head->extra = Z_NULL; state->mode = EXTRA; /* fallthrough */ case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != Z_NULL && state->head->extra != Z_NULL) { len = state->head->extra_len - state->length; zmemcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; /* fallthrough */ case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->name != Z_NULL && state->length < state->head->name_max) state->head->name[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->name = Z_NULL; state->length = 0; state->mode = COMMENT; /* fallthrough */ case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->comment != Z_NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->comment = Z_NULL; state->mode = HCRC; /* fallthrough */ case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if ((state->wrap & 4) && hold != (state->check & 0xffff)) { strm->msg = (char *)"header crc mismatch"; state->mode = BAD; break; } INITBITS(); } if (state->head != Z_NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = crc32(0L, Z_NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = ZSWAP32(hold); INITBITS(); state->mode = DICT; /* fallthrough */ case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = TYPE; /* fallthrough */ case TYPE: if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; /* fallthrough */ case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN_; /* decode codes */ if (flush == Z_TREES) { DROPBITS(2); goto inf_leave; } break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); state->mode = COPY_; if (flush == Z_TREES) goto inf_leave; /* fallthrough */ case COPY_: state->mode = COPY; /* fallthrough */ case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); state->have = 0; state->mode = LENLENS; /* fallthrough */ case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); state->have = 0; state->mode = CODELENS; /* fallthrough */ case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (const code FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN_; if (flush == Z_TREES) goto inf_leave; /* fallthrough */ case LEN_: state->mode = LEN; /* fallthrough */ case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); if (state->mode == TYPE) state->back = -1; break; } state->back = 0; for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; state->length = (unsigned)here.val; if ((int)(here.op) == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); state->mode = LIT; break; } if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->back = -1; state->mode = TYPE; break; } if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } state->extra = (unsigned)(here.op) & 15; state->mode = LENEXT; /* fallthrough */ case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } Tracevv((stderr, "inflate: length %u\n", state->length)); state->was = state->length; state->mode = DIST; /* fallthrough */ case DIST: for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; state->extra = (unsigned)(here.op) & 15; state->mode = DISTEXT; /* fallthrough */ case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif Tracevv((stderr, "inflate: distance %u\n", state->offset)); state->mode = MATCH; /* fallthrough */ case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR Trace((stderr, "inflate.c too far\n")); copy -= state->whave; if (copy > state->length) copy = state->length; if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = 0; } while (--copy); if (state->length == 0) state->mode = LEN; break; #endif } if (copy > state->wnext) { copy -= state->wnext; from = state->window + (state->wsize - copy); } else from = state->window + (state->wnext - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE_CHECK(state->check, put - out, out); out = left; if ((state->wrap & 4) && ( #ifdef GUNZIP state->flags ? hold : #endif ZSWAP32(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: check matches trailer\n")); } #ifdef GUNZIP state->mode = LENGTH; /* fallthrough */ case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) { strm->msg = (char *)"incorrect length check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: length matches trailer\n")); } #endif state->mode = DONE; /* fallthrough */ case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* fallthrough */ default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (out != strm->avail_out && state->mode < BAD && (state->mode < CHECK || flush != Z_FINISH))) if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += in; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE_CHECK(state->check, strm->next_out - out, out); strm->data_type = (int)state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0) + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; } int ZEXPORT inflateEnd(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->window != Z_NULL) ZFREE(strm, state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; } int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) z_streamp strm; Bytef *dictionary; uInt *dictLength; { struct inflate_state FAR *state; /* check state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* copy dictionary */ if (state->whave && dictionary != Z_NULL) { zmemcpy(dictionary, state->window + state->wnext, state->whave - state->wnext); zmemcpy(dictionary + state->whave - state->wnext, state->window, state->wnext); } if (dictLength != Z_NULL) *dictLength = state->whave; return Z_OK; } int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { struct inflate_state FAR *state; unsigned long dictid; int ret; /* check state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; /* check for correct dictionary identifier */ if (state->mode == DICT) { dictid = adler32(0L, Z_NULL, 0); dictid = adler32(dictid, dictionary, dictLength); if (dictid != state->check) return Z_DATA_ERROR; } /* copy dictionary to window using updatewindow(), which will amend the existing dictionary if appropriate */ ret = updatewindow(strm, dictionary + dictLength, dictLength); if (ret) { state->mode = MEM; return Z_MEM_ERROR; } state->havedict = 1; Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } int ZEXPORT inflateGetHeader(strm, head) z_streamp strm; gz_headerp head; { struct inflate_state FAR *state; /* check state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; /* save header structure */ state->head = head; head->done = 0; return Z_OK; } /* Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found or when out of input. When called, *have is the number of pattern bytes found in order so far, in 0..3. On return *have is updated to the new state. If on return *have equals four, then the pattern was found and the return value is how many bytes were read including the last byte of the pattern. If *have is less than four, then the pattern has not been found yet and the return value is len. In the latter case, syncsearch() can be called again with more data and the *have state. *have is initialized to zero for the first call. */ local unsigned syncsearch(have, buf, len) unsigned FAR *have; const unsigned char FAR *buf; unsigned len; { unsigned got; unsigned next; got = *have; next = 0; while (next < len && got < 4) { if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) got++; else if (buf[next]) got = 0; else got = 4 - got; next++; } *have = got; return next; } int ZEXPORT inflateSync(strm) z_streamp strm; { unsigned len; /* number of bytes to look at or looked at */ int flags; /* temporary to save header status */ unsigned long in, out; /* temporary to save total_in and total_out */ unsigned char buf[4]; /* to restore bit buffer to byte string */ struct inflate_state FAR *state; /* check parameters */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; /* if first time, start search in bit buffer */ if (state->mode != SYNC) { state->mode = SYNC; state->hold <<= state->bits & 7; state->bits -= state->bits & 7; len = 0; while (state->bits >= 8) { buf[len++] = (unsigned char)(state->hold); state->hold >>= 8; state->bits -= 8; } state->have = 0; syncsearch(&(state->have), buf, len); } /* search available input */ len = syncsearch(&(state->have), strm->next_in, strm->avail_in); strm->avail_in -= len; strm->next_in += len; strm->total_in += len; /* return no joy or set up to restart inflate() on a new block */ if (state->have != 4) return Z_DATA_ERROR; if (state->flags == -1) state->wrap = 0; /* if no header yet, treat as raw */ else state->wrap &= ~4; /* no point in computing a check value now */ flags = state->flags; in = strm->total_in; out = strm->total_out; inflateReset(strm); strm->total_in = in; strm->total_out = out; state->flags = flags; state->mode = TYPE; return Z_OK; } /* Returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored block. When decompressing, PPP checks that at the end of input packet, inflate is waiting for these length bytes. */ int ZEXPORT inflateSyncPoint(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; return state->mode == STORED && state->bits == 0; } int ZEXPORT inflateCopy(dest, source) z_streamp dest; z_streamp source; { struct inflate_state FAR *state; struct inflate_state FAR *copy; unsigned char FAR *window; unsigned wsize; /* check input */ if (inflateStateCheck(source) || dest == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)source->state; /* allocate space */ copy = (struct inflate_state FAR *) ZALLOC(source, 1, sizeof(struct inflate_state)); if (copy == Z_NULL) return Z_MEM_ERROR; window = Z_NULL; if (state->window != Z_NULL) { window = (unsigned char FAR *) ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); if (window == Z_NULL) { ZFREE(source, copy); return Z_MEM_ERROR; } } /* copy state */ zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); copy->strm = dest; if (state->lencode >= state->codes && state->lencode <= state->codes + ENOUGH - 1) { copy->lencode = copy->codes + (state->lencode - state->codes); copy->distcode = copy->codes + (state->distcode - state->codes); } copy->next = copy->codes + (state->next - state->codes); if (window != Z_NULL) { wsize = 1U << state->wbits; zmemcpy(window, state->window, wsize); } copy->window = window; dest->state = (struct internal_state FAR *)copy; return Z_OK; } int ZEXPORT inflateUndermine(strm, subvert) z_streamp strm; int subvert; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR state->sane = !subvert; return Z_OK; #else (void)subvert; state->sane = 1; return Z_DATA_ERROR; #endif } int ZEXPORT inflateValidate(strm, check) z_streamp strm; int check; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (check && state->wrap) state->wrap |= 4; else state->wrap &= ~4; return Z_OK; } long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return -(1L << 16); state = (struct inflate_state FAR *)strm->state; return (long)(((unsigned long)((long)state->back)) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } unsigned long ZEXPORT inflateCodesUsed(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return (unsigned long)-1; state = (struct inflate_state FAR *)strm->state; return (unsigned long)(state->next - state->codes); }
libgit2-main
deps/zlib/inflate.c
/* deflate.c -- compress data using the deflation algorithm * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process depends on being able to identify portions * of the input text which are identical to earlier input (within a * sliding window trailing behind the input currently being processed). * * The most straightforward technique turns out to be the fastest for * most input files: try all possible matches and select the longest. * The key feature of this algorithm is that insertions into the string * dictionary are very simple and thus fast, and deletions are avoided * completely. Insertions are performed at each input character, whereas * string matches are performed only when the previous match ends. So it * is preferable to spend more time in matches to allow very fast string * insertions and avoid deletions. The matching algorithm for small * strings is inspired from that of Rabin & Karp. A brute force approach * is used to find longer strings when a small match has been found. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze * (by Leonid Broukhis). * A previous version of this file used a more sophisticated algorithm * (by Fiala and Greene) which is guaranteed to run in linear amortized * time, but has a larger average cost, uses more memory and is patented. * However the F&G algorithm may be faster for some highly redundant * files if the parameter max_chain_length (described below) is too large. * * ACKNOWLEDGEMENTS * * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and * I found it in 'freeze' written by Leonid Broukhis. * Thanks to many people for bug reports and testing. * * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". * Available in http://tools.ietf.org/html/rfc1951 * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. * * Fiala,E.R., and Greene,D.H. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 * */ /* @(#) $Id$ */ #include "deflate.h" const char deflate_copyright[] = " deflate 1.2.12 Copyright 1995-2022 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* =========================================================================== * Function prototypes. */ typedef enum { need_more, /* block not completed, need more input or more output */ block_done, /* block flush performed */ finish_started, /* finish started, need only more output at next deflate */ finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) OF((deflate_state *s, int flush)); /* Compression function. Returns the block state after the call. */ local int deflateStateCheck OF((z_streamp strm)); local void slide_hash OF((deflate_state *s)); local void fill_window OF((deflate_state *s)); local block_state deflate_stored OF((deflate_state *s, int flush)); local block_state deflate_fast OF((deflate_state *s, int flush)); #ifndef FASTEST local block_state deflate_slow OF((deflate_state *s, int flush)); #endif local block_state deflate_rle OF((deflate_state *s, int flush)); local block_state deflate_huff OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifdef ASMV # pragma message("Assembler code may have bugs -- use at your own risk") void match_init OF((void)); /* asm code initialization */ uInt longest_match OF((deflate_state *s, IPos cur_match)); #else local uInt longest_match OF((deflate_state *s, IPos cur_match)); #endif #ifdef ZLIB_DEBUG local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif /* =========================================================================== * Local data */ #define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { ush good_length; /* reduce lazy search above this match length */ ush max_lazy; /* do not perform lazy search above this match length */ ush nice_length; /* quit search above this match length */ ush max_chain; compress_func func; } config; #ifdef FASTEST local const config configuration_table[2] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ #else local const config configuration_table[10] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, /* 3 */ {4, 6, 32, 32, deflate_fast}, /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ /* 5 */ {8, 16, 32, 32, deflate_slow}, /* 6 */ {8, 16, 128, 128, deflate_slow}, /* 7 */ {8, 32, 128, 256, deflate_slow}, /* 8 */ {32, 128, 258, 1024, deflate_slow}, /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ #endif /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to UPDATE_HASH are made with consecutive input * characters, so that a running hash key can be computed from the previous * key instead of complete recalculation each time. */ #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) /* =========================================================================== * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * If this file is compiled with -DFASTEST, the compression level is forced * to 1, and no hash chains are maintained. * IN assertion: all calls to INSERT_STRING are made with consecutive input * characters and the first MIN_MATCH bytes of str are valid (except for * the last MIN_MATCH-1 bytes of the input file). */ #ifdef FASTEST #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #else #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #endif /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ do { \ s->head[s->hash_size-1] = NIL; \ zmemzero((Bytef *)s->head, \ (unsigned)(s->hash_size-1)*sizeof(*s->head)); \ } while (0) /* =========================================================================== * Slide the hash table when sliding the window down (could be avoided with 32 * bit values at the expense of memory usage). We slide even when level == 0 to * keep the hash table consistent if we switch back to level > 0 later. */ #if defined(__has_feature) # if __has_feature(memory_sanitizer) __attribute__((no_sanitize("memory"))) # endif #endif local void slide_hash(s) deflate_state *s; { unsigned n, m; Posf *p; uInt wsize = s->w_size; n = s->hash_size; p = &s->head[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m - wsize : NIL); } while (--n); n = wsize; #ifndef FASTEST p = &s->prev[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m - wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); #endif } /* ========================================================================= */ int ZEXPORT deflateInit_(strm, level, version, stream_size) z_streamp strm; int level; const char *version; int stream_size; { return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size); /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, version, stream_size) z_streamp strm; int level; int method; int windowBits; int memLevel; int strategy; const char *version; int stream_size; { deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { return Z_VERSION_ERROR; } if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; if (strm->zalloc == (alloc_func)0) { #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; #endif } if (strm->zfree == (free_func)0) #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zfree = zcfree; #endif #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } #ifdef GZIP else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } #endif if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) { return Z_STREAM_ERROR; } if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); if (s == Z_NULL) return Z_MEM_ERROR; strm->state = (struct internal_state FAR *)s; s->strm = strm; s->status = INIT_STATE; /* to pass state test in deflateReset() */ s->wrap = wrap; s->gzhead = Z_NULL; s->w_bits = (uInt)windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; s->hash_bits = (uInt)memLevel + 7; s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); s->high_water = 0; /* nothing written to s->window yet */ s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ /* We overlay pending_buf and sym_buf. This works since the average size * for length/distance pairs over any compressed block is assured to be 31 * bits or less. * * Analysis: The longest fixed codes are a length code of 8 bits plus 5 * extra bits, for lengths 131 to 257. The longest fixed distance codes are * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest * possible fixed-codes length/distance pair is then 31 bits total. * * sym_buf starts one-fourth of the way into pending_buf. So there are * three bytes in sym_buf for every four bytes in pending_buf. Each symbol * in sym_buf is three bytes -- two for the distance and one for the * literal/length. As each symbol is consumed, the pointer to the next * sym_buf value to read moves forward three bytes. From that symbol, up to * 31 bits are written to pending_buf. The closest the written pending_buf * bits gets to the next sym_buf symbol to read is just before the last * code is written. At that time, 31*(n-2) bits have been written, just * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1 * symbols are written.) The closest the writing gets to what is unread is * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and * can range from 128 to 32768. * * Therefore, at a minimum, there are 142 bits of space between what is * written and what is read in the overlain buffers, so the symbols cannot * be overwritten by the compressed data. That space is actually 139 bits, * due to the three-bit fixed-code block header. * * That covers the case where either Z_FIXED is specified, forcing fixed * codes, or when the use of fixed codes is chosen, because that choice * results in a smaller compressed block than dynamic codes. That latter * condition then assures that the above analysis also covers all dynamic * blocks. A dynamic-code block will only be chosen to be emitted if it has * fewer bits than a fixed-code block would for the same set of symbols. * Therefore its average symbol length is assured to be less than 31. So * the compressed data for a dynamic block also cannot overwrite the * symbols from which it is being constructed. */ s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4); s->pending_buf_size = (ulg)s->lit_bufsize * 4; if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { s->status = FINISH_STATE; strm->msg = ERR_MSG(Z_MEM_ERROR); deflateEnd (strm); return Z_MEM_ERROR; } s->sym_buf = s->pending_buf + s->lit_bufsize; s->sym_end = (s->lit_bufsize - 1) * 3; /* We avoid equality with lit_bufsize*3 because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ s->level = level; s->strategy = strategy; s->method = (Byte)method; return deflateReset(strm); } /* ========================================================================= * Check for a valid deflate stream state. Return 0 if ok, 1 if not. */ local int deflateStateCheck (strm) z_streamp strm; { deflate_state *s; if (strm == Z_NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) return 1; s = strm->state; if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE && #ifdef GZIP s->status != GZIP_STATE && #endif s->status != EXTRA_STATE && s->status != NAME_STATE && s->status != COMMENT_STATE && s->status != HCRC_STATE && s->status != BUSY_STATE && s->status != FINISH_STATE)) return 1; return 0; } /* ========================================================================= */ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { deflate_state *s; uInt str, n; int wrap; unsigned avail; z_const unsigned char *next; if (deflateStateCheck(strm) || dictionary == Z_NULL) return Z_STREAM_ERROR; s = strm->state; wrap = s->wrap; if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) return Z_STREAM_ERROR; /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap == 1) strm->adler = adler32(strm->adler, dictionary, dictLength); s->wrap = 0; /* avoid computing Adler-32 in read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s->w_size) { if (wrap == 0) { /* already empty otherwise */ CLEAR_HASH(s); s->strstart = 0; s->block_start = 0L; s->insert = 0; } dictionary += dictLength - s->w_size; /* use the tail */ dictLength = s->w_size; } /* insert dictionary into window and hash */ avail = strm->avail_in; next = strm->next_in; strm->avail_in = dictLength; strm->next_in = (z_const Bytef *)dictionary; fill_window(s); while (s->lookahead >= MIN_MATCH) { str = s->strstart; n = s->lookahead - (MIN_MATCH-1); do { UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); #ifndef FASTEST s->prev[str & s->w_mask] = s->head[s->ins_h]; #endif s->head[s->ins_h] = (Pos)str; str++; } while (--n); s->strstart = str; s->lookahead = MIN_MATCH-1; fill_window(s); } s->strstart += s->lookahead; s->block_start = (long)s->strstart; s->insert = s->lookahead; s->lookahead = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; strm->next_in = next; strm->avail_in = avail; s->wrap = wrap; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) z_streamp strm; Bytef *dictionary; uInt *dictLength; { deflate_state *s; uInt len; if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; len = s->strstart + s->lookahead; if (len > s->w_size) len = s->w_size; if (dictionary != Z_NULL && len) zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len); if (dictLength != Z_NULL) *dictLength = len; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateResetKeep (strm) z_streamp strm; { deflate_state *s; if (deflateStateCheck(strm)) { return Z_STREAM_ERROR; } strm->total_in = strm->total_out = 0; strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ strm->data_type = Z_UNKNOWN; s = (deflate_state *)strm->state; s->pending = 0; s->pending_out = s->pending_buf; if (s->wrap < 0) { s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ } s->status = #ifdef GZIP s->wrap == 2 ? GZIP_STATE : #endif INIT_STATE; strm->adler = #ifdef GZIP s->wrap == 2 ? crc32(0L, Z_NULL, 0) : #endif adler32(0L, Z_NULL, 0); s->last_flush = -2; _tr_init(s); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateReset (strm) z_streamp strm; { int ret; ret = deflateResetKeep(strm); if (ret == Z_OK) lm_init(strm->state); return ret; } /* ========================================================================= */ int ZEXPORT deflateSetHeader (strm, head) z_streamp strm; gz_headerp head; { if (deflateStateCheck(strm) || strm->state->wrap != 2) return Z_STREAM_ERROR; strm->state->gzhead = head; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflatePending (strm, pending, bits) unsigned *pending; int *bits; z_streamp strm; { if (deflateStateCheck(strm)) return Z_STREAM_ERROR; if (pending != Z_NULL) *pending = strm->state->pending; if (bits != Z_NULL) *bits = strm->state->bi_valid; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflatePrime (strm, bits, value) z_streamp strm; int bits; int value; { deflate_state *s; int put; if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; if (bits < 0 || bits > 16 || s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3)) return Z_BUF_ERROR; do { put = Buf_size - s->bi_valid; if (put > bits) put = bits; s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); s->bi_valid += put; _tr_flush_bits(s); value >>= put; bits -= put; } while (bits); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateParams(strm, level, strategy) z_streamp strm; int level; int strategy; { deflate_state *s; compress_func func; if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } func = configuration_table[s->level].func; if ((strategy != s->strategy || func != configuration_table[level].func) && s->last_flush != -2) { /* Flush the last buffer: */ int err = deflate(strm, Z_BLOCK); if (err == Z_STREAM_ERROR) return err; if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead) return Z_BUF_ERROR; } if (s->level != level) { if (s->level == 0 && s->matches != 0) { if (s->matches == 1) slide_hash(s); else CLEAR_HASH(s); s->matches = 0; } s->level = level; s->max_lazy_match = configuration_table[level].max_lazy; s->good_match = configuration_table[level].good_length; s->nice_match = configuration_table[level].nice_length; s->max_chain_length = configuration_table[level].max_chain; } s->strategy = strategy; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) z_streamp strm; int good_length; int max_lazy; int nice_length; int max_chain; { deflate_state *s; if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; s->good_match = (uInt)good_length; s->max_lazy_match = (uInt)max_lazy; s->nice_match = nice_length; s->max_chain_length = (uInt)max_chain; return Z_OK; } /* ========================================================================= * For the default windowBits of 15 and memLevel of 8, this function returns * a close to exact, as well as small, upper bound on the compressed size. * They are coded as constants here for a reason--if the #define's are * changed, then this function needs to be changed as well. The return * value for 15 and 8 only works for those exact settings. * * For any setting other than those defaults for windowBits and memLevel, * the value returned is a conservative worst case for the maximum expansion * resulting from using fixed blocks instead of stored blocks, which deflate * can emit on compressed data for some combinations of the parameters. * * This function could be more sophisticated to provide closer upper bounds for * every combination of windowBits and memLevel. But even the conservative * upper bound of about 14% expansion does not seem onerous for output buffer * allocation. */ uLong ZEXPORT deflateBound(strm, sourceLen) z_streamp strm; uLong sourceLen; { deflate_state *s; uLong complen, wraplen; /* conservative upper bound for compressed data */ complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; /* if can't get parameters, return conservative bound plus zlib wrapper */ if (deflateStateCheck(strm)) return complen + 6; /* compute wrapper length */ s = strm->state; switch (s->wrap) { case 0: /* raw deflate */ wraplen = 0; break; case 1: /* zlib wrapper */ wraplen = 6 + (s->strstart ? 4 : 0); break; #ifdef GZIP case 2: /* gzip wrapper */ wraplen = 18; if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ Bytef *str; if (s->gzhead->extra != Z_NULL) wraplen += 2 + s->gzhead->extra_len; str = s->gzhead->name; if (str != Z_NULL) do { wraplen++; } while (*str++); str = s->gzhead->comment; if (str != Z_NULL) do { wraplen++; } while (*str++); if (s->gzhead->hcrc) wraplen += 2; } break; #endif default: /* for compiler happiness */ wraplen = 6; } /* if not default parameters, return conservative bound */ if (s->w_bits != 15 || s->hash_bits != 8 + 7) return complen + wraplen; /* default settings: return tight bound for that case */ return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13 - 6 + wraplen; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ local void putShortMSB (s, b) deflate_state *s; uInt b; { put_byte(s, (Byte)(b >> 8)); put_byte(s, (Byte)(b & 0xff)); } /* ========================================================================= * Flush as much pending output as possible. All deflate() output, except for * some deflate_stored() output, goes through this function so some * applications may wish to modify it to avoid allocating a large * strm->next_out buffer and copying into it. (See also read_buf()). */ local void flush_pending(strm) z_streamp strm; { unsigned len; deflate_state *s = strm->state; _tr_flush_bits(s); len = s->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; zmemcpy(strm->next_out, s->pending_out, len); strm->next_out += len; s->pending_out += len; strm->total_out += len; strm->avail_out -= len; s->pending -= len; if (s->pending == 0) { s->pending_out = s->pending_buf; } } /* =========================================================================== * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1]. */ #define HCRC_UPDATE(beg) \ do { \ if (s->gzhead->hcrc && s->pending > (beg)) \ strm->adler = crc32(strm->adler, s->pending_buf + (beg), \ s->pending - (beg)); \ } while (0) /* ========================================================================= */ int ZEXPORT deflate (strm, flush) z_streamp strm; int flush; { int old_flush; /* value of flush param for previous deflate call */ deflate_state *s; if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) { return Z_STREAM_ERROR; } s = strm->state; if (strm->next_out == Z_NULL || (strm->avail_in != 0 && strm->next_in == Z_NULL) || (s->status == FINISH_STATE && flush != Z_FINISH)) { ERR_RETURN(strm, Z_STREAM_ERROR); } if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); old_flush = s->last_flush; s->last_flush = flush; /* Flush as much pending output as possible */ if (s->pending != 0) { flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s->last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { ERR_RETURN(strm, Z_BUF_ERROR); } /* Write the header */ if (s->status == INIT_STATE && s->wrap == 0) s->status = BUSY_STATE; if (s->status == INIT_STATE) { /* zlib header */ uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; uInt level_flags; if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) level_flags = 0; else if (s->level < 6) level_flags = 1; else if (s->level == 6) level_flags = 2; else level_flags = 3; header |= (level_flags << 6); if (s->strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } strm->adler = adler32(0L, Z_NULL, 0); s->status = BUSY_STATE; /* Compression must start with an empty pending buffer */ flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } } #ifdef GZIP if (s->status == GZIP_STATE) { /* gzip header */ strm->adler = crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (s->gzhead == Z_NULL) { put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s->status = BUSY_STATE; /* Compression must start with an empty pending buffer */ flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } } else { put_byte(s, (s->gzhead->text ? 1 : 0) + (s->gzhead->hcrc ? 2 : 0) + (s->gzhead->extra == Z_NULL ? 0 : 4) + (s->gzhead->name == Z_NULL ? 0 : 8) + (s->gzhead->comment == Z_NULL ? 0 : 16) ); put_byte(s, (Byte)(s->gzhead->time & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, s->gzhead->os & 0xff); if (s->gzhead->extra != Z_NULL) { put_byte(s, s->gzhead->extra_len & 0xff); put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); } if (s->gzhead->hcrc) strm->adler = crc32(strm->adler, s->pending_buf, s->pending); s->gzindex = 0; s->status = EXTRA_STATE; } } if (s->status == EXTRA_STATE) { if (s->gzhead->extra != Z_NULL) { ulg beg = s->pending; /* start of bytes to update crc */ uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex; while (s->pending + left > s->pending_buf_size) { uInt copy = s->pending_buf_size - s->pending; zmemcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, copy); s->pending = s->pending_buf_size; HCRC_UPDATE(beg); s->gzindex += copy; flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } beg = 0; left -= copy; } zmemcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, left); s->pending += left; HCRC_UPDATE(beg); s->gzindex = 0; } s->status = NAME_STATE; } if (s->status == NAME_STATE) { if (s->gzhead->name != Z_NULL) { ulg beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { HCRC_UPDATE(beg); flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } beg = 0; } val = s->gzhead->name[s->gzindex++]; put_byte(s, val); } while (val != 0); HCRC_UPDATE(beg); s->gzindex = 0; } s->status = COMMENT_STATE; } if (s->status == COMMENT_STATE) { if (s->gzhead->comment != Z_NULL) { ulg beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { HCRC_UPDATE(beg); flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } beg = 0; } val = s->gzhead->comment[s->gzindex++]; put_byte(s, val); } while (val != 0); HCRC_UPDATE(beg); } s->status = HCRC_STATE; } if (s->status == HCRC_STATE) { if (s->gzhead->hcrc) { if (s->pending + 2 > s->pending_buf_size) { flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } } put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); strm->adler = crc32(0L, Z_NULL, 0); } s->status = BUSY_STATE; /* Compression must start with an empty pending buffer */ flush_pending(strm); if (s->pending != 0) { s->last_flush = -1; return Z_OK; } } #endif /* Start a new block or continue the current one. */ if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { block_state bstate; bstate = s->level == 0 ? deflate_stored(s, flush) : s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s->strategy == Z_RLE ? deflate_rle(s, flush) : (*(configuration_table[s->level].func))(s, flush); if (bstate == finish_started || bstate == finish_done) { s->status = FINISH_STATE; } if (bstate == need_more || bstate == finish_started) { if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate == block_done) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(s); } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ _tr_stored_block(s, (char*)0, 0L, 0); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush == Z_FULL_FLUSH) { CLEAR_HASH(s); /* forget history */ if (s->lookahead == 0) { s->strstart = 0; s->block_start = 0L; s->insert = 0; } } } flush_pending(strm); if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } if (flush != Z_FINISH) return Z_OK; if (s->wrap <= 0) return Z_STREAM_END; /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); put_byte(s, (Byte)(strm->total_in & 0xff)); put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); } else #endif { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ return s->pending != 0 ? Z_OK : Z_STREAM_END; } /* ========================================================================= */ int ZEXPORT deflateEnd (strm) z_streamp strm; { int status; if (deflateStateCheck(strm)) return Z_STREAM_ERROR; status = strm->state->status; /* Deallocate in reverse order of allocations: */ TRY_FREE(strm, strm->state->pending_buf); TRY_FREE(strm, strm->state->head); TRY_FREE(strm, strm->state->prev); TRY_FREE(strm, strm->state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; } /* ========================================================================= * Copy the source state to the destination state. * To simplify the source, this is not supported for 16-bit MSDOS (which * doesn't have enough memory anyway to duplicate compression states). */ int ZEXPORT deflateCopy (dest, source) z_streamp dest; z_streamp source; { #ifdef MAXSEG_64K return Z_STREAM_ERROR; #else deflate_state *ds; deflate_state *ss; if (deflateStateCheck(source) || dest == Z_NULL) { return Z_STREAM_ERROR; } ss = source->state; zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4); if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { deflateEnd (dest); return Z_MEM_ERROR; } /* following zmemcpy do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); ds->sym_buf = ds->pending_buf + ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; ds->bl_desc.dyn_tree = ds->bl_tree; return Z_OK; #endif /* MAXSEG_64K */ } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ local unsigned read_buf(strm, buf, size) z_streamp strm; Bytef *buf; unsigned size; { unsigned len = strm->avail_in; if (len > size) len = size; if (len == 0) return 0; strm->avail_in -= len; zmemcpy(buf, strm->next_in, len); if (strm->state->wrap == 1) { strm->adler = adler32(strm->adler, buf, len); } #ifdef GZIP else if (strm->state->wrap == 2) { strm->adler = crc32(strm->adler, buf, len); } #endif strm->next_in += len; strm->total_in += len; return len; } /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ local void lm_init (s) deflate_state *s; { s->window_size = (ulg)2L*s->w_size; CLEAR_HASH(s); /* Set the default configuration parameters: */ s->max_lazy_match = configuration_table[s->level].max_lazy; s->good_match = configuration_table[s->level].good_length; s->nice_match = configuration_table[s->level].nice_length; s->max_chain_length = configuration_table[s->level].max_chain; s->strstart = 0; s->block_start = 0L; s->lookahead = 0; s->insert = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; #ifndef FASTEST #ifdef ASMV match_init(); /* initialize the asm code */ #endif #endif } #ifndef FASTEST /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ #ifndef ASMV /* For 80x86 and 680x0, an optimized version will be provided in match.asm or * match.S. The code will be functionally equivalent. */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { unsigned chain_length = s->max_chain_length;/* max hash chain length */ register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ int best_len = (int)s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ Posf *prev = s->prev; uInt wmask = s->w_mask; #ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. * Try with and without -DUNALIGNED_OK to check. */ register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ushf*)scan; register ush scan_end = *(ushf*)(scan+best_len-1); #else register Bytef *strend = s->window + s->strstart + MAX_MATCH; register Byte scan_end1 = scan[best_len-1]; register Byte scan_end = scan[best_len]; #endif /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(unsigned short) == 2. Do not use * UNALIGNED_OK if your compiler uses a different size. */ if (*(ushf*)(match+best_len-1) != scan_end || *(ushf*)match != scan_start) continue; /* It is not necessary to compare scan[2] and match[2] since they are * always equal when the other bytes match, given that the hash keys * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at * strstart+3, +5, ... up to strstart+257. We check for insufficient * lookahead only every 4th comparison; the 128th check will be made * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is * necessary to put more guard bytes at the end of the window, or * to check more often for insufficient lookahead. */ Assert(scan[2] == match[2], "scan[2]?"); scan++, match++; do { } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && scan < strend); /* The funny "do {}" generates better code on most compilers */ /* Here, scan <= window+strstart+257 */ Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); if (*scan == *match) scan++; len = (MAX_MATCH - 1) - (int)(strend-scan); scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ if (match[best_len] != scan_end || match[best_len-1] != scan_end1 || *match != *scan || *++match != scan[1]) continue; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match++; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ if (len > best_len) { s->match_start = cur_match; best_len = len; if (len >= nice_match) break; #ifdef UNALIGNED_OK scan_end = *(ushf*)(scan+best_len-1); #else scan_end1 = scan[best_len-1]; scan_end = scan[best_len]; #endif } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length != 0); if ((uInt)best_len <= s->lookahead) return (uInt)best_len; return s->lookahead; } #endif /* ASMV */ #else /* FASTEST */ /* --------------------------------------------------------------------------- * Optimized version for FASTEST only */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ register Bytef *strend = s->window + s->strstart + MAX_MATCH; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Return failure if the match length is less than 2: */ if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match += 2; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); if (len < MIN_MATCH) return MIN_MATCH - 1; s->match_start = cur_match; return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; } #endif /* FASTEST */ #ifdef ZLIB_DEBUG #define EQUAL 0 /* result of memcmp for equal strings */ /* =========================================================================== * Check that the match at match_start is indeed a match. */ local void check_match(s, start, match, length) deflate_state *s; IPos start, match; int length; { /* check that the match is indeed a match */ if (zmemcmp(s->window + match, s->window + start, length) != EQUAL) { fprintf(stderr, " start %u, match %u, length %d\n", start, match, length); do { fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); } while (--length != 0); z_error("invalid match"); } if (z_verbose > 1) { fprintf(stderr,"\\[%d,%d]", start-match, length); do { putc(s->window[start++], stderr); } while (--length != 0); } } #else # define check_match(s, start, match, length) #endif /* ZLIB_DEBUG */ /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ local void fill_window(s) deflate_state *s; { unsigned n; unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); /* Deal with !@#$% 64K limit: */ if (sizeof(int) <= 2) { if (more == 0 && s->strstart == 0 && s->lookahead == 0) { more = wsize; } else if (more == (unsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if * strstart == 0 && lookahead == 1 (input done a byte at time) */ more--; } } /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s->strstart >= wsize+MAX_DIST(s)) { zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); s->match_start -= wsize; s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ s->block_start -= (long) wsize; if (s->insert > s->strstart) s->insert = s->strstart; slide_hash(s); more += wsize; } if (s->strm->avail_in == 0) break; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ Assert(more >= 2, "more < 2"); n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ if (s->lookahead + s->insert >= MIN_MATCH) { uInt str = s->strstart - s->insert; s->ins_h = s->window[str]; UPDATE_HASH(s, s->ins_h, s->window[str + 1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif while (s->insert) { UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); #ifndef FASTEST s->prev[str & s->w_mask] = s->head[s->ins_h]; #endif s->head[s->ins_h] = (Pos)str; str++; s->insert--; if (s->lookahead + s->insert < MIN_MATCH) break; } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ if (s->high_water < s->window_size) { ulg curr = s->strstart + (ulg)(s->lookahead); ulg init; if (s->high_water < curr) { /* Previous high water mark below current data -- zero WIN_INIT * bytes or up to end of window, whichever is less. */ init = s->window_size - curr; if (init > WIN_INIT) init = WIN_INIT; zmemzero(s->window + curr, (unsigned)init); s->high_water = curr + init; } else if (s->high_water < (ulg)curr + WIN_INIT) { /* High water mark at or above current data, but below current data * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up * to end of window, whichever is less. */ init = (ulg)curr + WIN_INIT - s->high_water; if (init > s->window_size - s->high_water) init = s->window_size - s->high_water; zmemzero(s->window + s->high_water, (unsigned)init); s->high_water += init; } } Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, "not enough room for search"); } /* =========================================================================== * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ #define FLUSH_BLOCK_ONLY(s, last) { \ _tr_flush_block(s, (s->block_start >= 0L ? \ (charf *)&s->window[(unsigned)s->block_start] : \ (charf *)Z_NULL), \ (ulg)((long)s->strstart - s->block_start), \ (last)); \ s->block_start = s->strstart; \ flush_pending(s->strm); \ Tracev((stderr,"[FLUSH]")); \ } /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, last) { \ FLUSH_BLOCK_ONLY(s, last); \ if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ } /* Maximum stored block length in deflate format (not including header). */ #define MAX_STORED 65535 /* Minimum of a and b. */ #define MIN(a, b) ((a) > (b) ? (b) : (a)) /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * * In case deflateParams() is used to later switch to a non-zero compression * level, s->matches (otherwise unused when storing) keeps track of the number * of hash table slides to perform. If s->matches is 1, then one hash table * slide will be done when switching. If s->matches is 2, the maximum value * allowed here, then the hash table will be cleared, since two or more slides * is the same as a clear. * * deflate_stored() is written to minimize the number of times an input byte is * copied. It is most efficient with large input and output buffers, which * maximizes the opportunites to have a single copy from next_in to next_out. */ local block_state deflate_stored(s, flush) deflate_state *s; int flush; { /* Smallest worthy block size when not flushing or finishing. By default * this is 32K. This can be as small as 507 bytes for memLevel == 1. For * large input and output buffers, the stored block size will be larger. */ unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size); /* Copy as many min_block or larger stored blocks directly to next_out as * possible. If flushing, copy the remaining available input to next_out as * stored blocks, if there is enough space. */ unsigned len, left, have, last = 0; unsigned used = s->strm->avail_in; do { /* Set len to the maximum size block that we can copy directly with the * available input data and output space. Set left to how much of that * would be copied from what's left in the window. */ len = MAX_STORED; /* maximum deflate stored block length */ have = (s->bi_valid + 42) >> 3; /* number of header bytes */ if (s->strm->avail_out < have) /* need room for header */ break; /* maximum stored block length that will fit in avail_out: */ have = s->strm->avail_out - have; left = s->strstart - s->block_start; /* bytes left in window */ if (len > (ulg)left + s->strm->avail_in) len = left + s->strm->avail_in; /* limit len to the input */ if (len > have) len = have; /* limit len to the output */ /* If the stored block would be less than min_block in length, or if * unable to copy all of the available input when flushing, then try * copying to the window and the pending buffer instead. Also don't * write an empty block when flushing -- deflate() does that. */ if (len < min_block && ((len == 0 && flush != Z_FINISH) || flush == Z_NO_FLUSH || len != left + s->strm->avail_in)) break; /* Make a dummy stored block in pending to get the header bytes, * including any pending bits. This also updates the debugging counts. */ last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0; _tr_stored_block(s, (char *)0, 0L, last); /* Replace the lengths in the dummy stored block with len. */ s->pending_buf[s->pending - 4] = len; s->pending_buf[s->pending - 3] = len >> 8; s->pending_buf[s->pending - 2] = ~len; s->pending_buf[s->pending - 1] = ~len >> 8; /* Write the stored block header bytes. */ flush_pending(s->strm); #ifdef ZLIB_DEBUG /* Update debugging counts for the data about to be copied. */ s->compressed_len += len << 3; s->bits_sent += len << 3; #endif /* Copy uncompressed bytes from the window to next_out. */ if (left) { if (left > len) left = len; zmemcpy(s->strm->next_out, s->window + s->block_start, left); s->strm->next_out += left; s->strm->avail_out -= left; s->strm->total_out += left; s->block_start += left; len -= left; } /* Copy uncompressed bytes directly from next_in to next_out, updating * the check value. */ if (len) { read_buf(s->strm, s->strm->next_out, len); s->strm->next_out += len; s->strm->avail_out -= len; s->strm->total_out += len; } } while (last == 0); /* Update the sliding window with the last s->w_size bytes of the copied * data, or append all of the copied data to the existing window if less * than s->w_size bytes were copied. Also update the number of bytes to * insert in the hash tables, in the event that deflateParams() switches to * a non-zero compression level. */ used -= s->strm->avail_in; /* number of input bytes directly copied */ if (used) { /* If any input was used, then no unused input remains in the window, * therefore s->block_start == s->strstart. */ if (used >= s->w_size) { /* supplant the previous history */ s->matches = 2; /* clear hash */ zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size); s->strstart = s->w_size; s->insert = s->strstart; } else { if (s->window_size - s->strstart <= used) { /* Slide the window down. */ s->strstart -= s->w_size; zmemcpy(s->window, s->window + s->w_size, s->strstart); if (s->matches < 2) s->matches++; /* add a pending slide_hash() */ if (s->insert > s->strstart) s->insert = s->strstart; } zmemcpy(s->window + s->strstart, s->strm->next_in - used, used); s->strstart += used; s->insert += MIN(used, s->w_size - s->insert); } s->block_start = s->strstart; } if (s->high_water < s->strstart) s->high_water = s->strstart; /* If the last block was written to next_out, then done. */ if (last) return finish_done; /* If flushing and all input has been consumed, then done. */ if (flush != Z_NO_FLUSH && flush != Z_FINISH && s->strm->avail_in == 0 && (long)s->strstart == s->block_start) return block_done; /* Fill the window with any remaining input. */ have = s->window_size - s->strstart; if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) { /* Slide the window down. */ s->block_start -= s->w_size; s->strstart -= s->w_size; zmemcpy(s->window, s->window + s->w_size, s->strstart); if (s->matches < 2) s->matches++; /* add a pending slide_hash() */ have += s->w_size; /* more space now */ if (s->insert > s->strstart) s->insert = s->strstart; } if (have > s->strm->avail_in) have = s->strm->avail_in; if (have) { read_buf(s->strm, s->window + s->strstart, have); s->strstart += have; s->insert += MIN(have, s->w_size - s->insert); } if (s->high_water < s->strstart) s->high_water = s->strstart; /* There was not enough avail_out to write a complete worthy or flushed * stored block to next_out. Write a stored block to pending instead, if we * have enough input for a worthy block, or if flushing and there is enough * room for the remaining input as a stored block in the pending buffer. */ have = (s->bi_valid + 42) >> 3; /* number of header bytes */ /* maximum stored block length that will fit in pending: */ have = MIN(s->pending_buf_size - have, MAX_STORED); min_block = MIN(have, s->w_size); left = s->strstart - s->block_start; if (left >= min_block || ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && s->strm->avail_in == 0 && left <= have)) { len = MIN(left, have); last = flush == Z_FINISH && s->strm->avail_in == 0 && len == left ? 1 : 0; _tr_stored_block(s, (charf *)s->window + s->block_start, len, last); s->block_start += len; flush_pending(s->strm); } /* We've done all we can with the available input and output. */ return last ? finish_started : need_more; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ local block_state deflate_fast(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ } if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->match_start, s->match_length); _tr_tally_dist(s, s->strstart - s->match_start, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ #ifndef FASTEST if (s->match_length <= s->max_insert_length && s->lookahead >= MIN_MATCH) { s->match_length--; /* string at strstart already in table */ do { s->strstart++; INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s->match_length != 0); s->strstart++; } else #endif { s->strstart += s->match_length; s->match_length = 0; s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } #ifndef FASTEST /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ local block_state deflate_slow(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED #if TOO_FAR <= 32767 || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) #endif )) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ check_match(s, s->strstart-1, s->prev_match, s->prev_length); _tr_tally_dist(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); if (bflush) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) { Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } #endif /* FASTEST */ /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ local block_state deflate_rle(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ uInt prev; /* byte at distance one to match */ Bytef *scan, *strend; /* scan goes up to strend for length of run */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s->lookahead <= MAX_MATCH) { fill_window(s); if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* See how many times the previous byte repeats */ s->match_length = 0; if (s->lookahead >= MIN_MATCH && s->strstart > 0) { scan = s->window + s->strstart - 1; prev = *scan; if (prev == *++scan && prev == *++scan && prev == *++scan) { strend = s->window + s->strstart + MAX_MATCH; do { } while (prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && scan < strend); s->match_length = MAX_MATCH - (uInt)(strend - scan); if (s->match_length > s->lookahead) s->match_length = s->lookahead; } Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->strstart - 1, s->match_length); _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; s->strstart += s->match_length; s->match_length = 0; } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } s->insert = 0; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ local block_state deflate_huff(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s->lookahead == 0) { fill_window(s); if (s->lookahead == 0) { if (flush == Z_NO_FLUSH) return need_more; break; /* flush the current block */ } } /* Output a literal byte */ s->match_length = 0; Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } s->insert = 0; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->sym_next) FLUSH_BLOCK(s, 0); return block_done; }
libgit2-main
deps/zlib/deflate.c
/* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-2022 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * This interleaved implementation of a CRC makes use of pipelined multiple * arithmetic-logic units, commonly found in modern CPU cores. It is due to * Kadatch and Jenkins (2010). See doc/crc-doc.1.0.pdf in this distribution. */ /* @(#) $Id$ */ /* Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore protection on the static variables used to control the first-use generation of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should first call get_crc_table() to initialize the tables before allowing more than one thread to use crc32(). MAKECRCH can be #defined to write out crc32.h. A main() routine is also produced, so that this one source file can be compiled to an executable. */ #ifdef MAKECRCH # include <stdio.h> # ifndef DYNAMIC_CRC_TABLE # define DYNAMIC_CRC_TABLE # endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ #include "zutil.h" /* for Z_U4, Z_U8, z_crc_t, and FAR definitions */ /* A CRC of a message is computed on N braids of words in the message, where each word consists of W bytes (4 or 8). If N is 3, for example, then three running sparse CRCs are calculated respectively on each braid, at these indices in the array of words: 0, 3, 6, ..., 1, 4, 7, ..., and 2, 5, 8, ... This is done starting at a word boundary, and continues until as many blocks of N * W bytes as are available have been processed. The results are combined into a single CRC at the end. For this code, N must be in the range 1..6 and W must be 4 or 8. The upper limit on N can be increased if desired by adding more #if blocks, extending the patterns apparent in the code. In addition, crc32.h would need to be regenerated, if the maximum N value is increased. N and W are chosen empirically by benchmarking the execution time on a given processor. The choices for N and W below were based on testing on Intel Kaby Lake i7, AMD Ryzen 7, ARM Cortex-A57, Sparc64-VII, PowerPC POWER9, and MIPS64 Octeon II processors. The Intel, AMD, and ARM processors were all fastest with N=5, W=8. The Sparc, PowerPC, and MIPS64 were all fastest at N=5, W=4. They were all tested with either gcc or clang, all using the -O3 optimization level. Your mileage may vary. */ /* Define N */ #ifdef Z_TESTN # define N Z_TESTN #else # define N 5 #endif #if N < 1 || N > 6 # error N must be in 1..6 #endif /* z_crc_t must be at least 32 bits. z_word_t must be at least as long as z_crc_t. It is assumed here that z_word_t is either 32 bits or 64 bits, and that bytes are eight bits. */ /* Define W and the associated z_word_t type. If W is not defined, then a braided calculation is not used, and the associated tables and code are not compiled. */ #ifdef Z_TESTW # if Z_TESTW-1 != -1 # define W Z_TESTW # endif #else # ifdef MAKECRCH # define W 8 /* required for MAKECRCH */ # else # if defined(__x86_64__) || defined(__aarch64__) # define W 8 # else # define W 4 # endif # endif #endif #ifdef W # if W == 8 && defined(Z_U8) typedef Z_U8 z_word_t; # elif defined(Z_U4) # undef W # define W 4 typedef Z_U4 z_word_t; # else # undef W # endif #endif /* Local functions. */ local z_crc_t multmodp OF((z_crc_t a, z_crc_t b)); local z_crc_t x2nmodp OF((z_off64_t n, unsigned k)); /* If available, use the ARM processor CRC32 instruction. */ #if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && W == 8 # define ARMCRC32 #endif #if defined(W) && (!defined(ARMCRC32) || defined(DYNAMIC_CRC_TABLE)) /* Swap the bytes in a z_word_t to convert between little and big endian. Any self-respecting compiler will optimize this to a single machine byte-swap instruction, if one is available. This assumes that word_t is either 32 bits or 64 bits. */ local z_word_t byte_swap(z_word_t word); local z_word_t byte_swap(word) z_word_t word; { # if W == 8 return (word & 0xff00000000000000) >> 56 | (word & 0xff000000000000) >> 40 | (word & 0xff0000000000) >> 24 | (word & 0xff00000000) >> 8 | (word & 0xff000000) << 8 | (word & 0xff0000) << 24 | (word & 0xff00) << 40 | (word & 0xff) << 56; # else /* W == 4 */ return (word & 0xff000000) >> 24 | (word & 0xff0000) >> 8 | (word & 0xff00) << 8 | (word & 0xff) << 24; # endif } #endif /* CRC polynomial. */ #define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */ #ifdef DYNAMIC_CRC_TABLE local z_crc_t FAR crc_table[256]; local z_crc_t FAR x2n_table[32]; local void make_crc_table OF((void)); #ifdef W local z_word_t FAR crc_big_table[256]; local z_crc_t FAR crc_braid_table[W][256]; local z_word_t FAR crc_braid_big_table[W][256]; local void braid OF((z_crc_t [][256], z_word_t [][256], int, int)); #endif #ifdef MAKECRCH local void write_table OF((FILE *, const z_crc_t FAR *, int)); local void write_table32hi OF((FILE *, const z_word_t FAR *, int)); local void write_table64 OF((FILE *, const z_word_t FAR *, int)); #endif /* MAKECRCH */ /* Define a once() function depending on the availability of atomics. If this is compiled with DYNAMIC_CRC_TABLE defined, and if CRCs will be computed in multiple threads, and if atomics are not available, then get_crc_table() must be called to initialize the tables and must return before any threads are allowed to compute or combine CRCs. */ /* Definition of once functionality. */ typedef struct once_s once_t; local void once OF((once_t *, void (*)(void))); /* Check for the availability of atomics. */ #if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \ !defined(__STDC_NO_ATOMICS__) #include <stdatomic.h> /* Structure for once(), which must be initialized with ONCE_INIT. */ struct once_s { atomic_flag begun; atomic_int done; }; #define ONCE_INIT {ATOMIC_FLAG_INIT, 0} /* Run the provided init() function exactly once, even if multiple threads invoke once() at the same time. The state must be a once_t initialized with ONCE_INIT. */ local void once(state, init) once_t *state; void (*init)(void); { if (!atomic_load(&state->done)) { if (atomic_flag_test_and_set(&state->begun)) while (!atomic_load(&state->done)) ; else { init(); atomic_store(&state->done, 1); } } } #else /* no atomics */ /* Structure for once(), which must be initialized with ONCE_INIT. */ struct once_s { volatile int begun; volatile int done; }; #define ONCE_INIT {0, 0} /* Test and set. Alas, not atomic, but tries to minimize the period of vulnerability. */ local int test_and_set OF((int volatile *)); local int test_and_set(flag) int volatile *flag; { int was; was = *flag; *flag = 1; return was; } /* Run the provided init() function once. This is not thread-safe. */ local void once(state, init) once_t *state; void (*init)(void); { if (!state->done) { if (test_and_set(&state->begun)) while (!state->done) ; else { init(); state->done = 1; } } } #endif /* State for once(). */ local once_t made = ONCE_INIT; /* Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x^2+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRCs on data a byte at a time for all combinations of CRC register values and incoming bytes. */ local void make_crc_table() { unsigned i, j, n; z_crc_t p; /* initialize the CRC of bytes tables */ for (i = 0; i < 256; i++) { p = i; for (j = 0; j < 8; j++) p = p & 1 ? (p >> 1) ^ POLY : p >> 1; crc_table[i] = p; #ifdef W crc_big_table[i] = byte_swap(p); #endif } /* initialize the x^2^n mod p(x) table */ p = (z_crc_t)1 << 30; /* x^1 */ x2n_table[0] = p; for (n = 1; n < 32; n++) x2n_table[n] = p = multmodp(p, p); #ifdef W /* initialize the braiding tables -- needs x2n_table[] */ braid(crc_braid_table, crc_braid_big_table, N, W); #endif #ifdef MAKECRCH { /* The crc32.h header file contains tables for both 32-bit and 64-bit z_word_t's, and so requires a 64-bit type be available. In that case, z_word_t must be defined to be 64-bits. This code then also generates and writes out the tables for the case that z_word_t is 32 bits. */ #if !defined(W) || W != 8 # error Need a 64-bit integer type in order to generate crc32.h. #endif FILE *out; int k, n; z_crc_t ltl[8][256]; z_word_t big[8][256]; out = fopen("crc32.h", "w"); if (out == NULL) return; /* write out little-endian CRC table to crc32.h */ fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n" " * Generated automatically by crc32.c\n */\n" "\n" "local const z_crc_t FAR crc_table[] = {\n" " "); write_table(out, crc_table, 256); fprintf(out, "};\n"); /* write out big-endian CRC table for 64-bit z_word_t to crc32.h */ fprintf(out, "\n" "#ifdef W\n" "\n" "#if W == 8\n" "\n" "local const z_word_t FAR crc_big_table[] = {\n" " "); write_table64(out, crc_big_table, 256); fprintf(out, "};\n"); /* write out big-endian CRC table for 32-bit z_word_t to crc32.h */ fprintf(out, "\n" "#else /* W == 4 */\n" "\n" "local const z_word_t FAR crc_big_table[] = {\n" " "); write_table32hi(out, crc_big_table, 256); fprintf(out, "};\n" "\n" "#endif\n"); /* write out braid tables for each value of N */ for (n = 1; n <= 6; n++) { fprintf(out, "\n" "#if N == %d\n", n); /* compute braid tables for this N and 64-bit word_t */ braid(ltl, big, n, 8); /* write out braid tables for 64-bit z_word_t to crc32.h */ fprintf(out, "\n" "#if W == 8\n" "\n" "local const z_crc_t FAR crc_braid_table[][256] = {\n"); for (k = 0; k < 8; k++) { fprintf(out, " {"); write_table(out, ltl[k], 256); fprintf(out, "}%s", k < 7 ? ",\n" : ""); } fprintf(out, "};\n" "\n" "local const z_word_t FAR crc_braid_big_table[][256] = {\n"); for (k = 0; k < 8; k++) { fprintf(out, " {"); write_table64(out, big[k], 256); fprintf(out, "}%s", k < 7 ? ",\n" : ""); } fprintf(out, "};\n"); /* compute braid tables for this N and 32-bit word_t */ braid(ltl, big, n, 4); /* write out braid tables for 32-bit z_word_t to crc32.h */ fprintf(out, "\n" "#else /* W == 4 */\n" "\n" "local const z_crc_t FAR crc_braid_table[][256] = {\n"); for (k = 0; k < 4; k++) { fprintf(out, " {"); write_table(out, ltl[k], 256); fprintf(out, "}%s", k < 3 ? ",\n" : ""); } fprintf(out, "};\n" "\n" "local const z_word_t FAR crc_braid_big_table[][256] = {\n"); for (k = 0; k < 4; k++) { fprintf(out, " {"); write_table32hi(out, big[k], 256); fprintf(out, "}%s", k < 3 ? ",\n" : ""); } fprintf(out, "};\n" "\n" "#endif\n" "\n" "#endif\n"); } fprintf(out, "\n" "#endif\n"); /* write out zeros operator table to crc32.h */ fprintf(out, "\n" "local const z_crc_t FAR x2n_table[] = {\n" " "); write_table(out, x2n_table, 32); fprintf(out, "};\n"); fclose(out); } #endif /* MAKECRCH */ } #ifdef MAKECRCH /* Write the 32-bit values in table[0..k-1] to out, five per line in hexadecimal separated by commas. */ local void write_table(out, table, k) FILE *out; const z_crc_t FAR *table; int k; { int n; for (n = 0; n < k; n++) fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ", (unsigned long)(table[n]), n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", ")); } /* Write the high 32-bits of each value in table[0..k-1] to out, five per line in hexadecimal separated by commas. */ local void write_table32hi(out, table, k) FILE *out; const z_word_t FAR *table; int k; { int n; for (n = 0; n < k; n++) fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ", (unsigned long)(table[n] >> 32), n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", ")); } /* Write the 64-bit values in table[0..k-1] to out, three per line in hexadecimal separated by commas. This assumes that if there is a 64-bit type, then there is also a long long integer type, and it is at least 64 bits. If not, then the type cast and format string can be adjusted accordingly. */ local void write_table64(out, table, k) FILE *out; const z_word_t FAR *table; int k; { int n; for (n = 0; n < k; n++) fprintf(out, "%s0x%016llx%s", n == 0 || n % 3 ? "" : " ", (unsigned long long)(table[n]), n == k - 1 ? "" : (n % 3 == 2 ? ",\n" : ", ")); } /* Actually do the deed. */ int main() { make_crc_table(); return 0; } #endif /* MAKECRCH */ #ifdef W /* Generate the little and big-endian braid tables for the given n and z_word_t size w. Each array must have room for w blocks of 256 elements. */ local void braid(ltl, big, n, w) z_crc_t ltl[][256]; z_word_t big[][256]; int n; int w; { int k; z_crc_t i, p, q; for (k = 0; k < w; k++) { p = x2nmodp((n * w + 3 - k) << 3, 0); ltl[k][0] = 0; big[w - 1 - k][0] = 0; for (i = 1; i < 256; i++) { ltl[k][i] = q = multmodp(i << 24, p); big[w - 1 - k][i] = byte_swap(q); } } } #endif #else /* !DYNAMIC_CRC_TABLE */ /* ======================================================================== * Tables for byte-wise and braided CRC-32 calculations, and a table of powers * of x for combining CRC-32s, all made by make_crc_table(). */ #include "crc32.h" #endif /* DYNAMIC_CRC_TABLE */ /* ======================================================================== * Routines used for CRC calculation. Some are also required for the table * generation above. */ /* Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, reflected. For speed, this requires that a not be zero. */ local z_crc_t multmodp(a, b) z_crc_t a; z_crc_t b; { z_crc_t m, p; m = (z_crc_t)1 << 31; p = 0; for (;;) { if (a & m) { p ^= b; if ((a & (m - 1)) == 0) break; } m >>= 1; b = b & 1 ? (b >> 1) ^ POLY : b >> 1; } return p; } /* Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been initialized. */ local z_crc_t x2nmodp(n, k) z_off64_t n; unsigned k; { z_crc_t p; p = (z_crc_t)1 << 31; /* x^0 == 1 */ while (n) { if (n & 1) p = multmodp(x2n_table[k & 31], p); n >>= 1; k++; } return p; } /* ========================================================================= * This function can be used by asm versions of crc32(), and to force the * generation of the CRC tables in a threaded application. */ const z_crc_t FAR * ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE once(&made, make_crc_table); #endif /* DYNAMIC_CRC_TABLE */ return (const z_crc_t FAR *)crc_table; } /* ========================================================================= * Use ARM machine instructions if available. This will compute the CRC about * ten times faster than the braided calculation. This code does not check for * the presence of the CRC instruction at run time. __ARM_FEATURE_CRC32 will * only be defined if the compilation specifies an ARM processor architecture * that has the instructions. For example, compiling with -march=armv8.1-a or * -march=armv8-a+crc, or -march=native if the compile machine has the crc32 * instructions. */ #ifdef ARMCRC32 /* Constants empirically determined to maximize speed. These values are from measurements on a Cortex-A57. Your mileage may vary. */ #define Z_BATCH 3990 /* number of words in a batch */ #define Z_BATCH_ZEROS 0xa10d3d0c /* computed from Z_BATCH = 3990 */ #define Z_BATCH_MIN 800 /* fewest words in a final batch */ unsigned long ZEXPORT crc32_z(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; z_size_t len; { z_crc_t val; z_word_t crc1, crc2; const z_word_t *word; z_word_t val0, val1, val2; z_size_t last, last2, i; z_size_t num; /* Return initial CRC, if requested. */ if (buf == Z_NULL) return 0; #ifdef DYNAMIC_CRC_TABLE once(&made, make_crc_table); #endif /* DYNAMIC_CRC_TABLE */ /* Pre-condition the CRC */ crc ^= 0xffffffff; /* Compute the CRC up to a word boundary. */ while (len && ((z_size_t)buf & 7) != 0) { len--; val = *buf++; __asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val)); } /* Prepare to compute the CRC on full 64-bit words word[0..num-1]. */ word = (z_word_t const *)buf; num = len >> 3; len &= 7; /* Do three interleaved CRCs to realize the throughput of one crc32x instruction per cycle. Each CRC is calcuated on Z_BATCH words. The three CRCs are combined into a single CRC after each set of batches. */ while (num >= 3 * Z_BATCH) { crc1 = 0; crc2 = 0; for (i = 0; i < Z_BATCH; i++) { val0 = word[i]; val1 = word[i + Z_BATCH]; val2 = word[i + 2 * Z_BATCH]; __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1)); __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2)); } word += 3 * Z_BATCH; num -= 3 * Z_BATCH; crc = multmodp(Z_BATCH_ZEROS, crc) ^ crc1; crc = multmodp(Z_BATCH_ZEROS, crc) ^ crc2; } /* Do one last smaller batch with the remaining words, if there are enough to pay for the combination of CRCs. */ last = num / 3; if (last >= Z_BATCH_MIN) { last2 = last << 1; crc1 = 0; crc2 = 0; for (i = 0; i < last; i++) { val0 = word[i]; val1 = word[i + last]; val2 = word[i + last2]; __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1)); __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2)); } word += 3 * last; num -= 3 * last; val = x2nmodp(last, 6); crc = multmodp(val, crc) ^ crc1; crc = multmodp(val, crc) ^ crc2; } /* Compute the CRC on any remaining words. */ for (i = 0; i < num; i++) { val0 = word[i]; __asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0)); } word += num; /* Complete the CRC on any remaining bytes. */ buf = (const unsigned char FAR *)word; while (len) { len--; val = *buf++; __asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val)); } /* Return the CRC, post-conditioned. */ return crc ^ 0xffffffff; } #else #ifdef W local z_crc_t crc_word(z_word_t data); local z_word_t crc_word_big(z_word_t data); /* Return the CRC of the W bytes in the word_t data, taking the least-significant byte of the word as the first byte of data, without any pre or post conditioning. This is used to combine the CRCs of each braid. */ local z_crc_t crc_word(data) z_word_t data; { int k; for (k = 0; k < W; k++) data = (data >> 8) ^ crc_table[data & 0xff]; return (z_crc_t)data; } local z_word_t crc_word_big(data) z_word_t data; { int k; for (k = 0; k < W; k++) data = (data << 8) ^ crc_big_table[(data >> ((W - 1) << 3)) & 0xff]; return data; } #endif /* ========================================================================= */ unsigned long ZEXPORT crc32_z(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; z_size_t len; { /* Return initial CRC, if requested. */ if (buf == Z_NULL) return 0; #ifdef DYNAMIC_CRC_TABLE once(&made, make_crc_table); #endif /* DYNAMIC_CRC_TABLE */ /* Pre-condition the CRC */ crc ^= 0xffffffff; #ifdef W /* If provided enough bytes, do a braided CRC calculation. */ if (len >= N * W + W - 1) { z_size_t blks; z_word_t const *words; unsigned endian; int k; /* Compute the CRC up to a z_word_t boundary. */ while (len && ((z_size_t)buf & (W - 1)) != 0) { len--; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; } /* Compute the CRC on as many N z_word_t blocks as are available. */ blks = len / (N * W); len -= blks * N * W; words = (z_word_t const *)buf; /* Do endian check at execution time instead of compile time, since ARM processors can change the endianess at execution time. If the compiler knows what the endianess will be, it can optimize out the check and the unused branch. */ endian = 1; if (*(unsigned char *)&endian) { /* Little endian. */ z_crc_t crc0; z_word_t word0; #if N > 1 z_crc_t crc1; z_word_t word1; #if N > 2 z_crc_t crc2; z_word_t word2; #if N > 3 z_crc_t crc3; z_word_t word3; #if N > 4 z_crc_t crc4; z_word_t word4; #if N > 5 z_crc_t crc5; z_word_t word5; #endif #endif #endif #endif #endif /* Initialize the CRC for each braid. */ crc0 = crc; #if N > 1 crc1 = 0; #if N > 2 crc2 = 0; #if N > 3 crc3 = 0; #if N > 4 crc4 = 0; #if N > 5 crc5 = 0; #endif #endif #endif #endif #endif /* Process the first blks-1 blocks, computing the CRCs on each braid independently. */ while (--blks) { /* Load the word for each braid into registers. */ word0 = crc0 ^ words[0]; #if N > 1 word1 = crc1 ^ words[1]; #if N > 2 word2 = crc2 ^ words[2]; #if N > 3 word3 = crc3 ^ words[3]; #if N > 4 word4 = crc4 ^ words[4]; #if N > 5 word5 = crc5 ^ words[5]; #endif #endif #endif #endif #endif words += N; /* Compute and update the CRC for each word. The loop should get unrolled. */ crc0 = crc_braid_table[0][word0 & 0xff]; #if N > 1 crc1 = crc_braid_table[0][word1 & 0xff]; #if N > 2 crc2 = crc_braid_table[0][word2 & 0xff]; #if N > 3 crc3 = crc_braid_table[0][word3 & 0xff]; #if N > 4 crc4 = crc_braid_table[0][word4 & 0xff]; #if N > 5 crc5 = crc_braid_table[0][word5 & 0xff]; #endif #endif #endif #endif #endif for (k = 1; k < W; k++) { crc0 ^= crc_braid_table[k][(word0 >> (k << 3)) & 0xff]; #if N > 1 crc1 ^= crc_braid_table[k][(word1 >> (k << 3)) & 0xff]; #if N > 2 crc2 ^= crc_braid_table[k][(word2 >> (k << 3)) & 0xff]; #if N > 3 crc3 ^= crc_braid_table[k][(word3 >> (k << 3)) & 0xff]; #if N > 4 crc4 ^= crc_braid_table[k][(word4 >> (k << 3)) & 0xff]; #if N > 5 crc5 ^= crc_braid_table[k][(word5 >> (k << 3)) & 0xff]; #endif #endif #endif #endif #endif } } /* Process the last block, combining the CRCs of the N braids at the same time. */ crc = crc_word(crc0 ^ words[0]); #if N > 1 crc = crc_word(crc1 ^ words[1] ^ crc); #if N > 2 crc = crc_word(crc2 ^ words[2] ^ crc); #if N > 3 crc = crc_word(crc3 ^ words[3] ^ crc); #if N > 4 crc = crc_word(crc4 ^ words[4] ^ crc); #if N > 5 crc = crc_word(crc5 ^ words[5] ^ crc); #endif #endif #endif #endif #endif words += N; } else { /* Big endian. */ z_word_t crc0, word0, comb; #if N > 1 z_word_t crc1, word1; #if N > 2 z_word_t crc2, word2; #if N > 3 z_word_t crc3, word3; #if N > 4 z_word_t crc4, word4; #if N > 5 z_word_t crc5, word5; #endif #endif #endif #endif #endif /* Initialize the CRC for each braid. */ crc0 = byte_swap(crc); #if N > 1 crc1 = 0; #if N > 2 crc2 = 0; #if N > 3 crc3 = 0; #if N > 4 crc4 = 0; #if N > 5 crc5 = 0; #endif #endif #endif #endif #endif /* Process the first blks-1 blocks, computing the CRCs on each braid independently. */ while (--blks) { /* Load the word for each braid into registers. */ word0 = crc0 ^ words[0]; #if N > 1 word1 = crc1 ^ words[1]; #if N > 2 word2 = crc2 ^ words[2]; #if N > 3 word3 = crc3 ^ words[3]; #if N > 4 word4 = crc4 ^ words[4]; #if N > 5 word5 = crc5 ^ words[5]; #endif #endif #endif #endif #endif words += N; /* Compute and update the CRC for each word. The loop should get unrolled. */ crc0 = crc_braid_big_table[0][word0 & 0xff]; #if N > 1 crc1 = crc_braid_big_table[0][word1 & 0xff]; #if N > 2 crc2 = crc_braid_big_table[0][word2 & 0xff]; #if N > 3 crc3 = crc_braid_big_table[0][word3 & 0xff]; #if N > 4 crc4 = crc_braid_big_table[0][word4 & 0xff]; #if N > 5 crc5 = crc_braid_big_table[0][word5 & 0xff]; #endif #endif #endif #endif #endif for (k = 1; k < W; k++) { crc0 ^= crc_braid_big_table[k][(word0 >> (k << 3)) & 0xff]; #if N > 1 crc1 ^= crc_braid_big_table[k][(word1 >> (k << 3)) & 0xff]; #if N > 2 crc2 ^= crc_braid_big_table[k][(word2 >> (k << 3)) & 0xff]; #if N > 3 crc3 ^= crc_braid_big_table[k][(word3 >> (k << 3)) & 0xff]; #if N > 4 crc4 ^= crc_braid_big_table[k][(word4 >> (k << 3)) & 0xff]; #if N > 5 crc5 ^= crc_braid_big_table[k][(word5 >> (k << 3)) & 0xff]; #endif #endif #endif #endif #endif } } /* Process the last block, combining the CRCs of the N braids at the same time. */ comb = crc_word_big(crc0 ^ words[0]); #if N > 1 comb = crc_word_big(crc1 ^ words[1] ^ comb); #if N > 2 comb = crc_word_big(crc2 ^ words[2] ^ comb); #if N > 3 comb = crc_word_big(crc3 ^ words[3] ^ comb); #if N > 4 comb = crc_word_big(crc4 ^ words[4] ^ comb); #if N > 5 comb = crc_word_big(crc5 ^ words[5] ^ comb); #endif #endif #endif #endif #endif words += N; crc = byte_swap(comb); } /* Update the pointer to the remaining bytes to process. */ buf = (unsigned char const *)words; } #endif /* W */ /* Complete the computation of the CRC on any remaining bytes. */ while (len >= 8) { len -= 8; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; } while (len) { len--; crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; } /* Return the CRC, post-conditioned. */ return crc ^ 0xffffffff; } #endif /* ========================================================================= */ unsigned long ZEXPORT crc32(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; uInt len; { return crc32_z(crc, buf, len); } /* ========================================================================= */ uLong ZEXPORT crc32_combine64(crc1, crc2, len2) uLong crc1; uLong crc2; z_off64_t len2; { #ifdef DYNAMIC_CRC_TABLE once(&made, make_crc_table); #endif /* DYNAMIC_CRC_TABLE */ return multmodp(x2nmodp(len2, 3), crc1) ^ crc2; } /* ========================================================================= */ uLong ZEXPORT crc32_combine(crc1, crc2, len2) uLong crc1; uLong crc2; z_off_t len2; { return crc32_combine64(crc1, crc2, len2); } /* ========================================================================= */ uLong ZEXPORT crc32_combine_gen64(len2) z_off64_t len2; { #ifdef DYNAMIC_CRC_TABLE once(&made, make_crc_table); #endif /* DYNAMIC_CRC_TABLE */ return x2nmodp(len2, 3); } /* ========================================================================= */ uLong ZEXPORT crc32_combine_gen(len2) z_off_t len2; { return crc32_combine_gen64(len2); } /* ========================================================================= */ uLong ZEXPORT crc32_combine_op(crc1, crc2, op) uLong crc1; uLong crc2; uLong op; { return multmodp(op, crc1) ^ crc2; }
libgit2-main
deps/zlib/crc32.c
/* infback.c -- inflate using a call-back interface * Copyright (C) 1995-2022 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* This code is largely copied from inflate.c. Normally either infback.o or inflate.o would be linked into an application--not both. The interface with inffast.c is retained so that optimized assembler-coded versions of inflate_fast() can be used with either inflate.c or infback.c. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); /* strm provides memory allocation functions in zalloc and zfree, or Z_NULL to use the library memory allocation functions. windowBits is in the range 8..15, and window is a user-supplied window and output buffer that is 2**windowBits bytes. */ int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) z_streamp strm; int windowBits; unsigned char FAR *window; const char *version; int stream_size; { struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL || window == Z_NULL || windowBits < 8 || windowBits > 15) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; #endif } if (strm->zfree == (free_func)0) #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zfree = zcfree; #endif state = (struct inflate_state FAR *)ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->dmax = 32768U; state->wbits = (uInt)windowBits; state->wsize = 1U << windowBits; state->window = window; state->wnext = 0; state->whave = 0; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } /* Macros for inflateBack(): */ /* Load returned state from inflate_fast() */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Set state from registers for inflate_fast() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Assure that some input is available. If input is requested, but denied, then return a Z_BUF_ERROR from inflateBack(). */ #define PULL() \ do { \ if (have == 0) { \ have = in(in_desc, &next); \ if (have == 0) { \ next = Z_NULL; \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflateBack() with an error if there is no input available. */ #define PULLBYTE() \ do { \ PULL(); \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflateBack() with an error. */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Assure that some output space is available, by writing out the window if it's full. If the write fails, return from inflateBack() with a Z_BUF_ERROR. */ #define ROOM() \ do { \ if (left == 0) { \ put = state->window; \ left = state->wsize; \ state->whave = left; \ if (out(out_desc, put, left)) { \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* strm provides the memory allocation functions and window buffer on input, and provides information on the unused input on return. For Z_DATA_ERROR returns, strm will also provide an error message. in() and out() are the call-back input and output functions. When inflateBack() needs more input, it calls in(). When inflateBack() has filled the window with output, or when it completes with data in the window, it calls out() to write out the data. The application must not change the provided input until in() is called again or inflateBack() returns. The application must not change the window/output buffer until inflateBack() returns. in() and out() are called with a descriptor parameter provided in the inflateBack() call. This parameter can be a structure that provides the information required to do the read or write, as well as accumulated information on the input and output such as totals and check values. in() should return zero on failure. out() should return non-zero on failure. If either in() or out() fails, than inflateBack() returns a Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it was in() or out() that caused in the error. Otherwise, inflateBack() returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format error, or Z_MEM_ERROR if it could not allocate memory for the state. inflateBack() can also return Z_STREAM_ERROR if the input parameters are not correct, i.e. strm is Z_NULL or the state was not initialized. */ int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) z_streamp strm; in_func in; void FAR *in_desc; out_func out; void FAR *out_desc; { struct inflate_state FAR *state; z_const unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* Check that the strm exists and that the state was initialized */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* Reset the state */ strm->msg = Z_NULL; state->mode = TYPE; state->last = 0; state->whave = 0; next = strm->next_in; have = next != Z_NULL ? strm->avail_in : 0; hold = 0; bits = 0; put = state->window; left = state->wsize; /* Inflate until end of block marked as last */ for (;;) switch (state->mode) { case TYPE: /* determine and dispatch block type */ if (state->last) { BYTEBITS(); state->mode = DONE; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN; /* decode codes */ break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: /* get and verify stored block length */ BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); /* copy stored block from input to output */ while (state->length != 0) { copy = state->length; PULL(); ROOM(); if (copy > have) copy = have; if (copy > left) copy = left; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: /* get dynamic table entries descriptor */ NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); /* get code length code lengths (not a typo) */ state->have = 0; while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); /* get length and distance code code lengths */ state->have = 0; while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = (unsigned)(state->lens[state->have - 1]); copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (code const FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN; /* fallthrough */ case LEN: /* use inflate_fast() if we have enough input and output */ if (have >= 6 && left >= 258) { RESTORE(); if (state->whave < state->wsize) state->whave = state->wsize - left; inflate_fast(strm, state->wsize); LOAD(); break; } /* get a literal, length, or end-of-block code */ for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(here.bits); state->length = (unsigned)here.val; /* process literal */ if (here.op == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); ROOM(); *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; } /* process end of block */ if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } /* invalid code */ if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } /* length code -- get extra bits, if any */ state->extra = (unsigned)(here.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); } Tracevv((stderr, "inflate: length %u\n", state->length)); /* get distance code */ for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(here.bits); if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; /* get distance extra bits, if any */ state->extra = (unsigned)(here.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); } if (state->offset > state->wsize - (state->whave < state->wsize ? left : 0)) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } Tracevv((stderr, "inflate: distance %u\n", state->offset)); /* copy match from window to output */ do { ROOM(); copy = state->wsize - state->offset; if (copy < left) { from = put + copy; copy = left - copy; } else { from = put - state->offset; copy = left; } if (copy > state->length) copy = state->length; state->length -= copy; left -= copy; do { *put++ = *from++; } while (--copy); } while (state->length != 0); break; case DONE: /* inflate stream terminated properly -- write leftover output */ ret = Z_STREAM_END; if (left < state->wsize) { if (out(out_desc, state->window, state->wsize - left)) ret = Z_BUF_ERROR; } goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; default: /* can't happen, but makes compilers happy */ ret = Z_STREAM_ERROR; goto inf_leave; } /* Return unused input */ inf_leave: strm->next_in = next; strm->avail_in = have; return ret; } int ZEXPORT inflateBackEnd(strm) z_streamp strm; { if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) return Z_STREAM_ERROR; ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; }
libgit2-main
deps/zlib/infback.c
/* zutil.c -- target dependent utility functions for the compression library * Copyright (C) 1995-2017 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" #ifndef Z_SOLO # include "gzguts.h" #endif z_const char * const z_errmsg[10] = { (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ (z_const char *)"stream end", /* Z_STREAM_END 1 */ (z_const char *)"", /* Z_OK 0 */ (z_const char *)"file error", /* Z_ERRNO (-1) */ (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ (z_const char *)"" }; const char * ZEXPORT zlibVersion() { return ZLIB_VERSION; } uLong ZEXPORT zlibCompileFlags() { uLong flags; flags = 0; switch ((int)(sizeof(uInt))) { case 2: break; case 4: flags += 1; break; case 8: flags += 2; break; default: flags += 3; } switch ((int)(sizeof(uLong))) { case 2: break; case 4: flags += 1 << 2; break; case 8: flags += 2 << 2; break; default: flags += 3 << 2; } switch ((int)(sizeof(voidpf))) { case 2: break; case 4: flags += 1 << 4; break; case 8: flags += 2 << 4; break; default: flags += 3 << 4; } switch ((int)(sizeof(z_off_t))) { case 2: break; case 4: flags += 1 << 6; break; case 8: flags += 2 << 6; break; default: flags += 3 << 6; } #ifdef ZLIB_DEBUG flags += 1 << 8; #endif #if defined(ASMV) || defined(ASMINF) flags += 1 << 9; #endif #ifdef ZLIB_WINAPI flags += 1 << 10; #endif #ifdef BUILDFIXED flags += 1 << 12; #endif #ifdef DYNAMIC_CRC_TABLE flags += 1 << 13; #endif #ifdef NO_GZCOMPRESS flags += 1L << 16; #endif #ifdef NO_GZIP flags += 1L << 17; #endif #ifdef PKZIP_BUG_WORKAROUND flags += 1L << 20; #endif #ifdef FASTEST flags += 1L << 21; #endif #if defined(STDC) || defined(Z_HAVE_STDARG_H) # ifdef NO_vsnprintf flags += 1L << 25; # ifdef HAS_vsprintf_void flags += 1L << 26; # endif # else # ifdef HAS_vsnprintf_void flags += 1L << 26; # endif # endif #else flags += 1L << 24; # ifdef NO_snprintf flags += 1L << 25; # ifdef HAS_sprintf_void flags += 1L << 26; # endif # else # ifdef HAS_snprintf_void flags += 1L << 26; # endif # endif #endif return flags; } #ifdef ZLIB_DEBUG #include <stdlib.h> # ifndef verbose # define verbose 0 # endif int ZLIB_INTERNAL z_verbose = verbose; void ZLIB_INTERNAL z_error (m) char *m; { fprintf(stderr, "%s\n", m); exit(1); } #endif /* exported to allow conversion of error code to string for compress() and * uncompress() */ const char * ZEXPORT zError(err) int err; { return ERR_MSG(err); } #if defined(_WIN32_WCE) && _WIN32_WCE < 0x800 /* The older Microsoft C Run-Time Library for Windows CE doesn't have * errno. We define it as a global variable to simplify porting. * Its value is always 0 and should not be used. */ int errno = 0; #endif #ifndef HAVE_MEMCPY void ZLIB_INTERNAL zmemcpy(dest, source, len) Bytef* dest; const Bytef* source; uInt len; { if (len == 0) return; do { *dest++ = *source++; /* ??? to be unrolled */ } while (--len != 0); } int ZLIB_INTERNAL zmemcmp(s1, s2, len) const Bytef* s1; const Bytef* s2; uInt len; { uInt j; for (j = 0; j < len; j++) { if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; } return 0; } void ZLIB_INTERNAL zmemzero(dest, len) Bytef* dest; uInt len; { if (len == 0) return; do { *dest++ = 0; /* ??? to be unrolled */ } while (--len != 0); } #endif #ifndef Z_SOLO #ifdef SYS16BIT #ifdef __TURBOC__ /* Turbo C in 16-bit mode */ # define MY_ZCALLOC /* Turbo C malloc() does not allow dynamic allocation of 64K bytes * and farmalloc(64K) returns a pointer with an offset of 8, so we * must fix the pointer. Warning: the pointer must be put back to its * original form in order to free it, use zcfree(). */ #define MAX_PTR 10 /* 10*64K = 640K */ local int next_ptr = 0; typedef struct ptr_table_s { voidpf org_ptr; voidpf new_ptr; } ptr_table; local ptr_table table[MAX_PTR]; /* This table is used to remember the original form of pointers * to large buffers (64K). Such pointers are normalized with a zero offset. * Since MSDOS is not a preemptive multitasking OS, this table is not * protected from concurrent access. This hack doesn't work anyway on * a protected system like OS/2. Use Microsoft C instead. */ voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) { voidpf buf; ulg bsize = (ulg)items*size; (void)opaque; /* If we allocate less than 65520 bytes, we assume that farmalloc * will return a usable pointer which doesn't have to be normalized. */ if (bsize < 65520L) { buf = farmalloc(bsize); if (*(ush*)&buf != 0) return buf; } else { buf = farmalloc(bsize + 16L); } if (buf == NULL || next_ptr >= MAX_PTR) return NULL; table[next_ptr].org_ptr = buf; /* Normalize the pointer to seg:0 */ *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; *(ush*)&buf = 0; table[next_ptr++].new_ptr = buf; return buf; } void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { int n; (void)opaque; if (*(ush*)&ptr != 0) { /* object < 64K */ farfree(ptr); return; } /* Find the original pointer */ for (n = 0; n < next_ptr; n++) { if (ptr != table[n].new_ptr) continue; farfree(table[n].org_ptr); while (++n < next_ptr) { table[n-1] = table[n]; } next_ptr--; return; } Assert(0, "zcfree: ptr not found"); } #endif /* __TURBOC__ */ #ifdef M_I86 /* Microsoft C in 16-bit mode */ # define MY_ZCALLOC #if (!defined(_MSC_VER) || (_MSC_VER <= 600)) # define _halloc halloc # define _hfree hfree #endif voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) { (void)opaque; return _halloc((long)items, size); } void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { (void)opaque; _hfree(ptr); } #endif /* M_I86 */ #endif /* SYS16BIT */ #ifndef MY_ZCALLOC /* Any system without a special alloc function */ #ifndef STDC extern voidp malloc OF((uInt size)); extern voidp calloc OF((uInt items, uInt size)); extern void free OF((voidpf ptr)); #endif voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) voidpf opaque; unsigned items; unsigned size; { (void)opaque; return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : (voidpf)calloc(items, size); } void ZLIB_INTERNAL zcfree (opaque, ptr) voidpf opaque; voidpf ptr; { (void)opaque; free(ptr); } #endif /* MY_ZCALLOC */ #endif /* !Z_SOLO */
libgit2-main
deps/zlib/zutil.c
/* inftrees.c -- generate Huffman trees for efficient decoding * Copyright (C) 1995-2022 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "zutil.h" #include "inftrees.h" #define MAXBITS 15 const char inflate_copyright[] = " inflate 1.2.12 Copyright 1995-2022 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* Build a set of tables to decode the provided canonical Huffman code. The code lengths are lens[0..codes-1]. The result starts at *table, whose indices are 0..2^bits-1. work is a writable array of at least lens shorts, which is used as a work area. type is the type of code to be generated, CODES, LENS, or DISTS. On return, zero is success, -1 is an invalid code, and +1 means that ENOUGH isn't enough. table on return points to the next available entry's address. bits is the requested root table index bits, and on return it is the actual root table index bits. It will differ if the request is greater than the longest code or if it is less than the shortest code. */ int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) codetype type; unsigned short FAR *lens; unsigned codes; code FAR * FAR *table; unsigned FAR *bits; unsigned short FAR *work; { unsigned len; /* a code's length in bits */ unsigned sym; /* index of code symbols */ unsigned min, max; /* minimum and maximum code lengths */ unsigned root; /* number of index bits for root table */ unsigned curr; /* number of index bits for current table */ unsigned drop; /* code bits to drop for sub-table */ int left; /* number of prefix codes available */ unsigned used; /* code entries in table used */ unsigned huff; /* Huffman code */ unsigned incr; /* for incrementing code, index */ unsigned fill; /* index for replicating entries */ unsigned low; /* low bits for current root entry */ unsigned mask; /* mask for low root bits */ code here; /* table entry for duplication */ code FAR *next; /* next available space in table */ const unsigned short FAR *base; /* base value table to use */ const unsigned short FAR *extra; /* extra bits table to use */ unsigned match; /* use base and extra for symbol >= match */ unsigned short count[MAXBITS+1]; /* number of codes of each length */ unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ static const unsigned short lbase[31] = { /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 199, 202}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64}; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) count[len] = 0; for (sym = 0; sym < codes; sym++) count[lens[sym]]++; /* bound code lengths, force root to be within code lengths */ root = *bits; for (max = MAXBITS; max >= 1; max--) if (count[max] != 0) break; if (root > max) root = max; if (max == 0) { /* no symbols to code at all */ here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)1; here.val = (unsigned short)0; *(*table)++ = here; /* make a table to force an error */ *(*table)++ = here; *bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) if (count[min] != 0) break; if (root < min) root = min; /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) return -1; /* over-subscribed */ } if (left > 0 && (type == CODES || max != 1)) return -1; /* incomplete set */ /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) offs[len + 1] = offs[len] + count[len]; /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ switch (type) { case CODES: base = extra = work; /* dummy value--not used */ match = 20; break; case LENS: base = lbase; extra = lext; match = 257; break; default: /* DISTS */ base = dbase; extra = dext; match = 0; } /* initialize state for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = *table; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = (unsigned)(-1); /* trigger new sub-table when len > root */ used = 1U << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type == LENS && used > ENOUGH_LENS) || (type == DISTS && used > ENOUGH_DISTS)) return 1; /* process all codes and make table entries */ for (;;) { /* create table entry */ here.bits = (unsigned char)(len - drop); if (work[sym] + 1U < match) { here.op = (unsigned char)0; here.val = work[sym]; } else if (work[sym] >= match) { here.op = (unsigned char)(extra[work[sym] - match]); here.val = base[work[sym] - match]; } else { here.op = (unsigned char)(32 + 64); /* end of block */ here.val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1U << (len - drop); fill = 1U << curr; min = fill; /* save offset to next table */ do { fill -= incr; next[(huff >> drop) + fill] = here; } while (fill != 0); /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; /* go to next symbol, update count, len */ sym++; if (--(count[len]) == 0) { if (len == max) break; len = lens[work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) != low) { /* if first time, transition to sub-tables */ if (drop == 0) drop = root; /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = (int)(1 << curr); while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) break; curr++; left <<= 1; } /* check for enough space */ used += 1U << curr; if ((type == LENS && used > ENOUGH_LENS) || (type == DISTS && used > ENOUGH_DISTS)) return 1; /* point entry in root table to sub-table */ low = huff & mask; (*table)[low].op = (unsigned char)curr; (*table)[low].bits = (unsigned char)root; (*table)[low].val = (unsigned short)(next - *table); } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff != 0) { here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)(len - drop); here.val = (unsigned short)0; next[huff] = here; } /* set return parameters */ *table += used; *bits = root; return 0; }
libgit2-main
deps/zlib/inftrees.c
/* trees.c -- output deflated data using Huffman coding * Copyright (C) 1995-2021 Jean-loup Gailly * detect_data_type() function provided freely by Cosmin Truta, 2006 * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process uses several Huffman trees. The more * common source values are represented by shorter bit sequences. * * Each code tree is stored in a compressed form which is itself * a Huffman encoding of the lengths of all the code strings (in * ascending order by source values). The actual code strings are * reconstructed from the lengths in the inflate process, as described * in the deflate specification. * * REFERENCES * * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc * * Storer, James A. * Data Compression: Methods and Theory, pp. 49-50. * Computer Science Press, 1988. ISBN 0-7167-8156-5. * * Sedgewick, R. * Algorithms, p290. * Addison-Wesley, 1983. ISBN 0-201-06672-6. */ /* @(#) $Id$ */ /* #define GEN_TREES_H */ #include "deflate.h" #ifdef ZLIB_DEBUG # include <ctype.h> #endif /* =========================================================================== * Constants */ #define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ #define END_BLOCK 256 /* end of block literal code */ #define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ #define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ #define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; local const int extra_dbits[D_CODES] /* extra bits for each distance code */ = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; local const uch bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ #define DIST_CODE_LEN 512 /* see definition of array dist_code below */ #if defined(GEN_TREES_H) || !defined(STDC) /* non ANSI compilers may not accept trees.h */ local ct_data static_ltree[L_CODES+2]; /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ local ct_data static_dtree[D_CODES]; /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ uch _dist_code[DIST_CODE_LEN]; /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ uch _length_code[MAX_MATCH-MIN_MATCH+1]; /* length code for each normalized match length (0 == MIN_MATCH) */ local int base_length[LENGTH_CODES]; /* First normalized length for each code (0 = MIN_MATCH) */ local int base_dist[D_CODES]; /* First normalized distance for each code (0 = distance of 1) */ #else # include "trees.h" #endif /* GEN_TREES_H */ struct static_tree_desc_s { const ct_data *static_tree; /* static tree or NULL */ const intf *extra_bits; /* extra bits for each code or NULL */ int extra_base; /* base index for extra_bits */ int elems; /* max number of elements in the tree */ int max_length; /* max bit length for the codes */ }; local const static_tree_desc static_l_desc = {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; local const static_tree_desc static_d_desc = {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; local const static_tree_desc static_bl_desc = {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; /* =========================================================================== * Local (static) routines in this file. */ local void tr_static_init OF((void)); local void init_block OF((deflate_state *s)); local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); local void build_tree OF((deflate_state *s, tree_desc *desc)); local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); local int build_bl_tree OF((deflate_state *s)); local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, int blcodes)); local void compress_block OF((deflate_state *s, const ct_data *ltree, const ct_data *dtree)); local int detect_data_type OF((deflate_state *s)); local unsigned bi_reverse OF((unsigned code, int len)); local void bi_windup OF((deflate_state *s)); local void bi_flush OF((deflate_state *s)); #ifdef GEN_TREES_H local void gen_trees_header OF((void)); #endif #ifndef ZLIB_DEBUG # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) /* Send a code of the given tree. c and tree must not have side effects */ #else /* !ZLIB_DEBUG */ # define send_code(s, c, tree) \ { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ send_bits(s, tree[c].Code, tree[c].Len); } #endif /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ #define put_short(s, w) { \ put_byte(s, (uch)((w) & 0xff)); \ put_byte(s, (uch)((ush)(w) >> 8)); \ } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ #ifdef ZLIB_DEBUG local void send_bits OF((deflate_state *s, int value, int length)); local void send_bits(s, value, length) deflate_state *s; int value; /* value to send */ int length; /* number of bits */ { Tracevv((stderr," l %2d v %4x ", length, value)); Assert(length > 0 && length <= 15, "invalid length"); s->bits_sent += (ulg)length; /* If not enough room in bi_buf, use (valid) bits from bi_buf and * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) * unused bits in value. */ if (s->bi_valid > (int)Buf_size - length) { s->bi_buf |= (ush)value << s->bi_valid; put_short(s, s->bi_buf); s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); s->bi_valid += length - Buf_size; } else { s->bi_buf |= (ush)value << s->bi_valid; s->bi_valid += length; } } #else /* !ZLIB_DEBUG */ #define send_bits(s, value, length) \ { int len = length;\ if (s->bi_valid > (int)Buf_size - len) {\ int val = (int)value;\ s->bi_buf |= (ush)val << s->bi_valid;\ put_short(s, s->bi_buf);\ s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ s->bi_valid += len - Buf_size;\ } else {\ s->bi_buf |= (ush)(value) << s->bi_valid;\ s->bi_valid += len;\ }\ } #endif /* ZLIB_DEBUG */ /* the arguments must not have side effects */ /* =========================================================================== * Initialize the various 'constant' tables. */ local void tr_static_init() { #if defined(GEN_TREES_H) || !defined(STDC) static int static_init_done = 0; int n; /* iterates over tree elements */ int bits; /* bit counter */ int length; /* length value */ int code; /* code value */ int dist; /* distance index */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ #ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = (uch)code; } } Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = (uch)code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; n = 0; while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n].Len = 5; static_dtree[n].Code = bi_reverse((unsigned)n, 5); } static_init_done = 1; # ifdef GEN_TREES_H gen_trees_header(); # endif #endif /* defined(GEN_TREES_H) || !defined(STDC) */ } /* =========================================================================== * Genererate the file trees.h describing the static trees. */ #ifdef GEN_TREES_H # ifndef ZLIB_DEBUG # include <stdio.h> # endif # define SEPARATOR(i, last, width) \ ((i) == (last)? "\n};\n\n" : \ ((i) % (width) == (width)-1 ? ",\n" : ", ")) void gen_trees_header() { FILE *header = fopen("trees.h", "w"); int i; Assert (header != NULL, "Can't open trees.h"); fprintf(header, "/* header created automatically with -DGEN_TREES_H */\n\n"); fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); for (i = 0; i < L_CODES+2; i++) { fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); } fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); for (i = 0; i < D_CODES; i++) { fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); } fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); for (i = 0; i < DIST_CODE_LEN; i++) { fprintf(header, "%2u%s", _dist_code[i], SEPARATOR(i, DIST_CODE_LEN-1, 20)); } fprintf(header, "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { fprintf(header, "%2u%s", _length_code[i], SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); } fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); for (i = 0; i < LENGTH_CODES; i++) { fprintf(header, "%1u%s", base_length[i], SEPARATOR(i, LENGTH_CODES-1, 20)); } fprintf(header, "local const int base_dist[D_CODES] = {\n"); for (i = 0; i < D_CODES; i++) { fprintf(header, "%5u%s", base_dist[i], SEPARATOR(i, D_CODES-1, 10)); } fclose(header); } #endif /* GEN_TREES_H */ /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ void ZLIB_INTERNAL _tr_init(s) deflate_state *s; { tr_static_init(); s->l_desc.dyn_tree = s->dyn_ltree; s->l_desc.stat_desc = &static_l_desc; s->d_desc.dyn_tree = s->dyn_dtree; s->d_desc.stat_desc = &static_d_desc; s->bl_desc.dyn_tree = s->bl_tree; s->bl_desc.stat_desc = &static_bl_desc; s->bi_buf = 0; s->bi_valid = 0; #ifdef ZLIB_DEBUG s->compressed_len = 0L; s->bits_sent = 0L; #endif /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Initialize a new block. */ local void init_block(s) deflate_state *s; { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; s->sym_next = s->matches = 0; } #define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ /* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ #define pqremove(s, tree, top) \ {\ top = s->heap[SMALLEST]; \ s->heap[SMALLEST] = s->heap[s->heap_len--]; \ pqdownheap(s, tree, SMALLEST); \ } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ #define smaller(tree, n, m, depth) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ local void pqdownheap(s, tree, k) deflate_state *s; ct_data *tree; /* the tree to restore */ int k; /* node to move down */ { int v = s->heap[k]; int j = k << 1; /* left son of k */ while (j <= s->heap_len) { /* Set j to the smallest of the two sons: */ if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s->heap[j], s->depth)) break; /* Exchange v with the smallest son */ s->heap[k] = s->heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s->heap[k] = v; } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ local void gen_bitlen(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; int max_code = desc->max_code; const ct_data *stree = desc->stat_desc->static_tree; const intf *extra = desc->stat_desc->extra_bits; int base = desc->stat_desc->extra_base; int max_length = desc->stat_desc->max_length; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ ush f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ for (h = s->heap_max+1; h < HEAP_SIZE; h++) { n = s->heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (ush)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ s->bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; s->opt_len += (ulg)f * (unsigned)(bits + xbits); if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); } if (overflow == 0) return; Tracev((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s->bl_count[bits] == 0) bits--; s->bl_count[bits]--; /* move one leaf down the tree */ s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ s->bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = s->bl_count[bits]; while (n != 0) { m = s->heap[--h]; if (m > max_code) continue; if ((unsigned) tree[m].Len != (unsigned) bits) { Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; tree[m].Len = (ush)bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ local void gen_codes (tree, max_code, bl_count) ct_data *tree; /* the tree to decorate */ int max_code; /* largest code with non zero frequency */ ushf *bl_count; /* number of codes at each bit length */ { ush next_code[MAX_BITS+1]; /* next code value for each bit length */ unsigned code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { code = (code + bl_count[bits-1]) << 1; next_code[bits] = (ush)code; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, "inconsistent bit counts"); Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n].Len; if (len == 0) continue; /* Now reverse the bits */ tree[n].Code = (ush)bi_reverse(next_code[len]++, len); Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ local void build_tree(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; const ct_data *stree = desc->stat_desc->static_tree; int elems = desc->stat_desc->elems; int n, m; /* iterate over heap elements */ int max_code = -1; /* largest code with non zero frequency */ int node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s->heap_len = 0, s->heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n].Freq != 0) { s->heap[++(s->heap_len)] = max_code = n; s->depth[n] = 0; } else { tree[n].Len = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s->heap_len < 2) { node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); tree[node].Freq = 1; s->depth[node] = 0; s->opt_len--; if (stree) s->static_len -= stree[node].Len; /* node is 0 or 1 so it does not have extra bits */ } desc->max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { pqremove(s, tree, n); /* n = node of least frequency */ m = s->heap[SMALLEST]; /* m = node of next least frequency */ s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ s->heap[--(s->heap_max)] = m; /* Create a new node father of n and m */ tree[node].Freq = tree[n].Freq + tree[m].Freq; s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? s->depth[n] : s->depth[m]) + 1); tree[n].Dad = tree[m].Dad = (ush)node; #ifdef DUMP_BL_TREE if (tree == s->bl_tree) { fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); } #endif /* and insert the new node in the heap */ s->heap[SMALLEST] = node++; pqdownheap(s, tree, SMALLEST); } while (s->heap_len >= 2); s->heap[--(s->heap_max)] = s->heap[SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, (tree_desc *)desc); /* The field len is now set, we can generate the bit codes */ gen_codes ((ct_data *)tree, max_code, s->bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ local void scan_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ if (nextlen == 0) max_count = 138, min_count = 3; tree[max_code+1].Len = (ush)0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { s->bl_tree[curlen].Freq += count; } else if (curlen != 0) { if (curlen != prevlen) s->bl_tree[curlen].Freq++; s->bl_tree[REP_3_6].Freq++; } else if (count <= 10) { s->bl_tree[REPZ_3_10].Freq++; } else { s->bl_tree[REPZ_11_138].Freq++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ local void send_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen == 0) max_count = 138, min_count = 3; for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s->bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(s, curlen, s->bl_tree); count--; } Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ local int build_bl_tree(s) deflate_state *s; { int max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); /* Build the bit length tree: */ build_tree(s, (tree_desc *)(&(s->bl_desc))); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; } /* Update opt_len to include the bit length tree and counts */ s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ local void send_all_trees(s, lcodes, dcodes, blcodes) deflate_state *s; int lcodes, dcodes, blcodes; /* number of codes for each tree */ { int rank; /* index in bl_order */ Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes"); Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); } Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Send a stored block */ void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block */ ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ bi_windup(s); /* align on byte boundary */ put_short(s, (ush)stored_len); put_short(s, (ush)~stored_len); if (stored_len) zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); s->pending += stored_len; #ifdef ZLIB_DEBUG s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; s->compressed_len += (stored_len + 4) << 3; s->bits_sent += 2*16; s->bits_sent += stored_len<<3; #endif } /* =========================================================================== * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) */ void ZLIB_INTERNAL _tr_flush_bits(s) deflate_state *s; { bi_flush(s); } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ void ZLIB_INTERNAL _tr_align(s) deflate_state *s; { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); #ifdef ZLIB_DEBUG s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ #endif bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and write out the encoded block. */ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block, or NULL if too old */ ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { /* Check if the file is binary or text */ if (s->strm->data_type == Z_UNKNOWN) s->strm->data_type = detect_data_type(s); /* Construct the literal and distance trees */ build_tree(s, (tree_desc *)(&(s->l_desc))); Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, s->static_len)); build_tree(s, (tree_desc *)(&(s->d_desc))); Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s->opt_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3; Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, s->sym_next / 3)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } #ifdef FORCE_STORED if (buf != (char*)0) { /* force stored block */ #else if (stored_len+4 <= opt_lenb && buf != (char*)0) { /* 4: two words for the lengths */ #endif /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); #ifdef FORCE_STATIC } else if (static_lenb >= 0) { /* force static trees */ #else } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { #endif send_bits(s, (STATIC_TREES<<1)+last, 3); compress_block(s, (const ct_data *)static_ltree, (const ct_data *)static_dtree); #ifdef ZLIB_DEBUG s->compressed_len += 3 + s->static_len; #endif } else { send_bits(s, (DYN_TREES<<1)+last, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); compress_block(s, (const ct_data *)s->dyn_ltree, (const ct_data *)s->dyn_dtree); #ifdef ZLIB_DEBUG s->compressed_len += 3 + s->opt_len; #endif } Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); #ifdef ZLIB_DEBUG s->compressed_len += 7; /* align on byte boundary */ #endif } Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ int ZLIB_INTERNAL _tr_tally (s, dist, lc) deflate_state *s; unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { s->sym_buf[s->sym_next++] = (uch)dist; s->sym_buf[s->sym_next++] = (uch)(dist >> 8); s->sym_buf[s->sym_next++] = (uch)lc; if (dist == 0) { /* lc is the unmatched char */ s->dyn_ltree[lc].Freq++; } else { s->matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ Assert((ush)dist < (ush)MAX_DIST(s) && (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; s->dyn_dtree[d_code(dist)].Freq++; } return (s->sym_next == s->sym_end); } /* =========================================================================== * Send the block data compressed using the given Huffman trees */ local void compress_block(s, ltree, dtree) deflate_state *s; const ct_data *ltree; /* literal tree */ const ct_data *dtree; /* distance tree */ { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ unsigned sx = 0; /* running index in sym_buf */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ if (s->sym_next != 0) do { dist = s->sym_buf[sx++] & 0xff; dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; lc = s->sym_buf[sx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra != 0) { dist -= (unsigned)base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and sym_buf is ok: */ Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); } while (sx < s->sym_next); send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "block list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ local int detect_data_type(s) deflate_state *s; { /* block_mask is the bit mask of block-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ unsigned long block_mask = 0xf3ffc07fUL; int n; /* Check for non-textual ("block-listed") bytes. */ for (n = 0; n <= 31; n++, block_mask >>= 1) if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) return Z_BINARY; /* Check for textual ("allow-listed") bytes. */ if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0) return Z_TEXT; for (n = 32; n < LITERALS; n++) if (s->dyn_ltree[n].Freq != 0) return Z_TEXT; /* There are no "block-listed" or "allow-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ local unsigned bi_reverse(code, len) unsigned code; /* the value to invert */ int len; /* its bit length */ { register unsigned res = 0; do { res |= code & 1; code >>= 1, res <<= 1; } while (--len > 0); return res >> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ local void bi_flush(s) deflate_state *s; { if (s->bi_valid == 16) { put_short(s, s->bi_buf); s->bi_buf = 0; s->bi_valid = 0; } else if (s->bi_valid >= 8) { put_byte(s, (Byte)s->bi_buf); s->bi_buf >>= 8; s->bi_valid -= 8; } } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ local void bi_windup(s) deflate_state *s; { if (s->bi_valid > 8) { put_short(s, s->bi_buf); } else if (s->bi_valid > 0) { put_byte(s, (Byte)s->bi_buf); } s->bi_buf = 0; s->bi_valid = 0; #ifdef ZLIB_DEBUG s->bits_sent = (s->bits_sent+7) & ~7; #endif }
libgit2-main
deps/zlib/trees.c
/* inffast.c -- fast decoding * Copyright (C) 1995-2017 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifdef ASMINF # pragma message("Assembler code may have bugs -- use at your own risk") #else /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state->mode == LEN strm->avail_in >= 6 strm->avail_out >= 258 start >= strm->avail_out state->bits < 8 On return, state->mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for output space. */ void ZLIB_INTERNAL inflate_fast(strm, start) z_streamp strm; unsigned start; /* inflate()'s starting value for strm->avail_out */ { struct inflate_state FAR *state; z_const unsigned char FAR *in; /* local strm->next_in */ z_const unsigned char FAR *last; /* have enough input while in < last */ unsigned char FAR *out; /* local strm->next_out */ unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ unsigned char FAR *end; /* while out < end, enough space available */ #ifdef INFLATE_STRICT unsigned dmax; /* maximum distance from zlib header */ #endif unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned wnext; /* window write index */ unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ unsigned long hold; /* local strm->hold */ unsigned bits; /* local strm->bits */ code const FAR *lcode; /* local strm->lencode */ code const FAR *dcode; /* local strm->distcode */ unsigned lmask; /* mask for first level of length codes */ unsigned dmask; /* mask for first level of distance codes */ code const *here; /* retrieved table entry */ unsigned op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ unsigned len; /* match length, unused bytes */ unsigned dist; /* match distance */ unsigned char FAR *from; /* where to copy match from */ /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; in = strm->next_in; last = in + (strm->avail_in - 5); out = strm->next_out; beg = out - (start - strm->avail_out); end = out + (strm->avail_out - 257); #ifdef INFLATE_STRICT dmax = state->dmax; #endif wsize = state->wsize; whave = state->whave; wnext = state->wnext; window = state->window; hold = state->hold; bits = state->bits; lcode = state->lencode; dcode = state->distcode; lmask = (1U << state->lenbits) - 1; dmask = (1U << state->distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ do { if (bits < 15) { hold += (unsigned long)(*in++) << bits; bits += 8; hold += (unsigned long)(*in++) << bits; bits += 8; } here = lcode + (hold & lmask); dolen: op = (unsigned)(here->bits); hold >>= op; bits -= op; op = (unsigned)(here->op); if (op == 0) { /* literal */ Tracevv((stderr, here->val >= 0x20 && here->val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here->val)); *out++ = (unsigned char)(here->val); } else if (op & 16) { /* length base */ len = (unsigned)(here->val); op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += (unsigned long)(*in++) << bits; bits += 8; } len += (unsigned)hold & ((1U << op) - 1); hold >>= op; bits -= op; } Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += (unsigned long)(*in++) << bits; bits += 8; hold += (unsigned long)(*in++) << bits; bits += 8; } here = dcode + (hold & dmask); dodist: op = (unsigned)(here->bits); hold >>= op; bits -= op; op = (unsigned)(here->op); if (op & 16) { /* distance base */ dist = (unsigned)(here->val); op &= 15; /* number of extra bits */ if (bits < op) { hold += (unsigned long)(*in++) << bits; bits += 8; if (bits < op) { hold += (unsigned long)(*in++) << bits; bits += 8; } } dist += (unsigned)hold & ((1U << op) - 1); #ifdef INFLATE_STRICT if (dist > dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif hold >>= op; bits -= op; Tracevv((stderr, "inflate: distance %u\n", dist)); op = (unsigned)(out - beg); /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR if (len <= op - whave) { do { *out++ = 0; } while (--len); continue; } len -= op - whave; do { *out++ = 0; } while (--op > whave); if (op == 0) { from = out - dist; do { *out++ = *from++; } while (--len); continue; } #endif } from = window; if (wnext == 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { *out++ = *from++; } while (--op); from = out - dist; /* rest from output */ } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { *out++ = *from++; } while (--op); from = window; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { *out++ = *from++; } while (--op); from = out - dist; /* rest from output */ } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { *out++ = *from++; } while (--op); from = out - dist; /* rest from output */ } } while (len > 2) { *out++ = *from++; *out++ = *from++; *out++ = *from++; len -= 3; } if (len) { *out++ = *from++; if (len > 1) *out++ = *from++; } } else { from = out - dist; /* copy direct from output */ do { /* minimum length is three */ *out++ = *from++; *out++ = *from++; *out++ = *from++; len -= 3; } while (len > 2); if (len) { *out++ = *from++; if (len > 1) *out++ = *from++; } } } else if ((op & 64) == 0) { /* 2nd level distance code */ here = dcode + here->val + (hold & ((1U << op) - 1)); goto dodist; } else { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } } else if ((op & 64) == 0) { /* 2nd level length code */ here = lcode + here->val + (hold & ((1U << op) - 1)); goto dolen; } else if (op & 32) { /* end-of-block */ Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } else { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } } while (in < last && out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; in -= len; bits -= len << 3; hold &= (1U << bits) - 1; /* update state and return */ strm->next_in = in; strm->next_out = out; strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); strm->avail_out = (unsigned)(out < end ? 257 + (end - out) : 257 - (out - end)); state->hold = hold; state->bits = bits; return; } /* inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - Using bit fields for code structure - Different op definition to avoid & for extra bits (do & for table bits) - Three separate decoding do-loops for direct, window, and wnext == 0 - Special case for distance > 1 copies to do overlapped load and store copy - Explicit branch predictions (based on measured branch probabilities) - Deferring match copy and interspersed it with decoding subsequent codes - Swapping literal/length else - Swapping window/direct else - Larger unrolled copy loops (three is about right) - Moving len -= 3 statement into middle of loop */ #endif /* !ASMINF */
libgit2-main
deps/zlib/inffast.c
/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2011, 2016 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); #define BASE 65521U /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* use NO_DIVIDE if your processor does not do division in hardware -- try it both ways to see which is faster */ #ifdef NO_DIVIDE /* note that this assumes BASE is 65521, where 65536 % 65521 == 15 (thank you to John Reiser for pointing this out) */ # define CHOP(a) \ do { \ unsigned long tmp = a >> 16; \ a &= 0xffffUL; \ a += (tmp << 4) - tmp; \ } while (0) # define MOD28(a) \ do { \ CHOP(a); \ if (a >= BASE) a -= BASE; \ } while (0) # define MOD(a) \ do { \ CHOP(a); \ MOD28(a); \ } while (0) # define MOD63(a) \ do { /* this assumes a is not negative */ \ z_off64_t tmp = a >> 32; \ a &= 0xffffffffL; \ a += (tmp << 8) - (tmp << 5) + tmp; \ tmp = a >> 16; \ a &= 0xffffL; \ a += (tmp << 4) - tmp; \ tmp = a >> 16; \ a &= 0xffffL; \ a += (tmp << 4) - tmp; \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE # define MOD28(a) a %= BASE # define MOD63(a) a %= BASE #endif /* ========================================================================= */ uLong ZEXPORT adler32_z(adler, buf, len) uLong adler; const Bytef *buf; z_size_t len; { unsigned long sum2; unsigned n; /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; /* in case user likes doing a byte at a time, keep it fast */ if (len == 1) { adler += buf[0]; if (adler >= BASE) adler -= BASE; sum2 += adler; if (sum2 >= BASE) sum2 -= BASE; return adler | (sum2 << 16); } /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { while (len--) { adler += *buf++; sum2 += adler; } if (adler >= BASE) adler -= BASE; MOD28(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } /* do length NMAX blocks -- requires just one modulo operation */ while (len >= NMAX) { len -= NMAX; n = NMAX / 16; /* NMAX is divisible by 16 */ do { DO16(buf); /* 16 sums unrolled */ buf += 16; } while (--n); MOD(adler); MOD(sum2); } /* do remaining bytes (less than NMAX, still just one modulo) */ if (len) { /* avoid modulos if none remaining */ while (len >= 16) { len -= 16; DO16(buf); buf += 16; } while (len--) { adler += *buf++; sum2 += adler; } MOD(adler); MOD(sum2); } /* return recombined sums */ return adler | (sum2 << 16); } /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { return adler32_z(adler, buf, len); } /* ========================================================================= */ local uLong adler32_combine_(adler1, adler2, len2) uLong adler1; uLong adler2; z_off64_t len2; { unsigned long sum1; unsigned long sum2; unsigned rem; /* for negative len, return invalid adler32 as a clue for debugging */ if (len2 < 0) return 0xffffffffUL; /* the derivation of this formula is left as an exercise for the reader */ MOD63(len2); /* assumes len2 >= 0 */ rem = (unsigned)len2; sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); sum1 += (adler2 & 0xffff) + BASE - 1; sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; if (sum1 >= BASE) sum1 -= BASE; if (sum1 >= BASE) sum1 -= BASE; if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1); if (sum2 >= BASE) sum2 -= BASE; return sum1 | (sum2 << 16); } /* ========================================================================= */ uLong ZEXPORT adler32_combine(adler1, adler2, len2) uLong adler1; uLong adler2; z_off_t len2; { return adler32_combine_(adler1, adler2, len2); } uLong ZEXPORT adler32_combine64(adler1, adler2, len2) uLong adler1; uLong adler2; z_off64_t len2; { return adler32_combine_(adler1, adler2, len2); }
libgit2-main
deps/zlib/adler32.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2020 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This module contains the external function pcre_compile(), along with supporting internal functions that are not used by other modules. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define NLBLOCK cd /* Block containing newline information */ #define PSSTART start_pattern /* Field containing pattern start */ #define PSEND end_pattern /* Field containing pattern end */ #include "pcre_internal.h" /* When PCRE_DEBUG is defined, we need the pcre(16|32)_printint() function, which is also used by pcretest. PCRE_DEBUG is not defined when building a production library. We do not need to select pcre16_printint.c specially, because the COMPILE_PCREx macro will already be appropriately set. */ #ifdef PCRE_DEBUG /* pcre_printint.c should not include any headers */ #define PCRE_INCLUDED #include "pcre_printint.c" #undef PCRE_INCLUDED #endif /* Macro for setting individual bits in class bitmaps. */ #define SETBIT(a,b) a[(b)/8] |= (1U << ((b)&7)) /* Maximum length value to check against when making sure that the integer that holds the compiled pattern length does not overflow. We make it a bit less than INT_MAX to allow for adding in group terminating bytes, so that we don't have to check them every time. */ #define OFLOW_MAX (INT_MAX - 20) /* Definitions to allow mutual recursion */ static int add_list_to_class(pcre_uint8 *, pcre_uchar **, int, compile_data *, const pcre_uint32 *, unsigned int); static BOOL compile_regex(int, pcre_uchar **, const pcre_uchar **, int *, BOOL, BOOL, int, int, pcre_uint32 *, pcre_int32 *, pcre_uint32 *, pcre_int32 *, branch_chain *, compile_data *, int *); /************************************************* * Code parameters and static tables * *************************************************/ /* This value specifies the size of stack workspace that is used during the first pre-compile phase that determines how much memory is required. The regex is partly compiled into this space, but the compiled parts are discarded as soon as they can be, so that hopefully there will never be an overrun. The code does, however, check for an overrun. The largest amount I've seen used is 218, so this number is very generous. The same workspace is used during the second, actual compile phase for remembering forward references to groups so that they can be filled in at the end. Each entry in this list occupies LINK_SIZE bytes, so even when LINK_SIZE is 4 there is plenty of room for most patterns. However, the memory can get filled up by repetitions of forward references, for example patterns like /(?1){0,1999}(b)/, and one user did hit the limit. The code has been changed so that the workspace is expanded using malloc() in this situation. The value below is therefore a minimum, and we put a maximum on it for safety. The minimum is now also defined in terms of LINK_SIZE so that the use of malloc() kicks in at the same number of forward references in all cases. */ #define COMPILE_WORK_SIZE (2048*LINK_SIZE) #define COMPILE_WORK_SIZE_MAX (100*COMPILE_WORK_SIZE) /* This value determines the size of the initial vector that is used for remembering named groups during the pre-compile. It is allocated on the stack, but if it is too small, it is expanded using malloc(), in a similar way to the workspace. The value is the number of slots in the list. */ #define NAMED_GROUP_LIST_SIZE 20 /* The overrun tests check for a slightly smaller size so that they detect the overrun before it actually does run off the end of the data block. */ #define WORK_SIZE_SAFETY_MARGIN (100) /* Private flags added to firstchar and reqchar. */ #define REQ_CASELESS (1U << 0) /* Indicates caselessness */ #define REQ_VARY (1U << 1) /* Reqchar followed non-literal item */ /* Negative values for the firstchar and reqchar flags */ #define REQ_UNSET (-2) #define REQ_NONE (-1) /* Repeated character flags. */ #define UTF_LENGTH 0x10000000l /* The char contains its length. */ /* Table for handling escaped characters in the range '0'-'z'. Positive returns are simple data values; negative values are for special things like \d and so on. Zero means further processing is needed (for things like \x), or the escape is invalid. */ #ifndef EBCDIC /* This is the "normal" table for ASCII systems or for EBCDIC systems running in UTF-8 mode. */ static const short int escapes[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, CHAR_COLON, CHAR_SEMICOLON, CHAR_LESS_THAN_SIGN, CHAR_EQUALS_SIGN, CHAR_GREATER_THAN_SIGN, CHAR_QUESTION_MARK, CHAR_COMMERCIAL_AT, -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E, 0, -ESC_G, -ESC_H, 0, 0, -ESC_K, 0, 0, -ESC_N, 0, -ESC_P, -ESC_Q, -ESC_R, -ESC_S, 0, 0, -ESC_V, -ESC_W, -ESC_X, 0, -ESC_Z, CHAR_LEFT_SQUARE_BRACKET, CHAR_BACKSLASH, CHAR_RIGHT_SQUARE_BRACKET, CHAR_CIRCUMFLEX_ACCENT, CHAR_UNDERSCORE, CHAR_GRAVE_ACCENT, ESC_a, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, -ESC_h, 0, 0, -ESC_k, 0, 0, ESC_n, 0, -ESC_p, 0, ESC_r, -ESC_s, ESC_tee, 0, -ESC_v, -ESC_w, 0, 0, -ESC_z }; #else /* This is the "abnormal" table for EBCDIC systems without UTF-8 support. */ static const short int escapes[] = { /* 48 */ 0, 0, 0, '.', '<', '(', '+', '|', /* 50 */ '&', 0, 0, 0, 0, 0, 0, 0, /* 58 */ 0, 0, '!', '$', '*', ')', ';', '~', /* 60 */ '-', '/', 0, 0, 0, 0, 0, 0, /* 68 */ 0, 0, '|', ',', '%', '_', '>', '?', /* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, /* 78 */ 0, '`', ':', '#', '@', '\'', '=', '"', /* 80 */ 0, ESC_a, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, /* 88 */-ESC_h, 0, 0, '{', 0, 0, 0, 0, /* 90 */ 0, 0, -ESC_k, 0, 0, ESC_n, 0, -ESC_p, /* 98 */ 0, ESC_r, 0, '}', 0, 0, 0, 0, /* A0 */ 0, '~', -ESC_s, ESC_tee, 0,-ESC_v, -ESC_w, 0, /* A8 */ 0,-ESC_z, 0, 0, 0, '[', 0, 0, /* B0 */ 0, 0, 0, 0, 0, 0, 0, 0, /* B8 */ 0, 0, 0, 0, 0, ']', '=', '-', /* C0 */ '{',-ESC_A, -ESC_B, -ESC_C, -ESC_D,-ESC_E, 0, -ESC_G, /* C8 */-ESC_H, 0, 0, 0, 0, 0, 0, 0, /* D0 */ '}', 0, -ESC_K, 0, 0,-ESC_N, 0, -ESC_P, /* D8 */-ESC_Q,-ESC_R, 0, 0, 0, 0, 0, 0, /* E0 */ '\\', 0, -ESC_S, 0, 0,-ESC_V, -ESC_W, -ESC_X, /* E8 */ 0,-ESC_Z, 0, 0, 0, 0, 0, 0, /* F0 */ 0, 0, 0, 0, 0, 0, 0, 0, /* F8 */ 0, 0, 0, 0, 0, 0, 0, 0 }; /* We also need a table of characters that may follow \c in an EBCDIC environment for characters 0-31. */ static unsigned char ebcdic_escape_c[] = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"; #endif /* Table of special "verbs" like (*PRUNE). This is a short table, so it is searched linearly. Put all the names into a single string, in order to reduce the number of relocations when a shared library is dynamically linked. The string is built from string macros so that it works in UTF-8 mode on EBCDIC platforms. */ typedef struct verbitem { int len; /* Length of verb name */ int op; /* Op when no arg, or -1 if arg mandatory */ int op_arg; /* Op when arg present, or -1 if not allowed */ } verbitem; static const char verbnames[] = "\0" /* Empty name is a shorthand for MARK */ STRING_MARK0 STRING_ACCEPT0 STRING_COMMIT0 STRING_F0 STRING_FAIL0 STRING_PRUNE0 STRING_SKIP0 STRING_THEN; static const verbitem verbs[] = { { 0, -1, OP_MARK }, { 4, -1, OP_MARK }, { 6, OP_ACCEPT, -1 }, { 6, OP_COMMIT, -1 }, { 1, OP_FAIL, -1 }, { 4, OP_FAIL, -1 }, { 5, OP_PRUNE, OP_PRUNE_ARG }, { 4, OP_SKIP, OP_SKIP_ARG }, { 4, OP_THEN, OP_THEN_ARG } }; static const int verbcount = sizeof(verbs)/sizeof(verbitem); /* Substitutes for [[:<:]] and [[:>:]], which mean start and end of word in another regex library. */ static const pcre_uchar sub_start_of_word[] = { CHAR_BACKSLASH, CHAR_b, CHAR_LEFT_PARENTHESIS, CHAR_QUESTION_MARK, CHAR_EQUALS_SIGN, CHAR_BACKSLASH, CHAR_w, CHAR_RIGHT_PARENTHESIS, '\0' }; static const pcre_uchar sub_end_of_word[] = { CHAR_BACKSLASH, CHAR_b, CHAR_LEFT_PARENTHESIS, CHAR_QUESTION_MARK, CHAR_LESS_THAN_SIGN, CHAR_EQUALS_SIGN, CHAR_BACKSLASH, CHAR_w, CHAR_RIGHT_PARENTHESIS, '\0' }; /* Tables of names of POSIX character classes and their lengths. The names are now all in a single string, to reduce the number of relocations when a shared library is dynamically loaded. The list of lengths is terminated by a zero length entry. The first three must be alpha, lower, upper, as this is assumed for handling case independence. The indices for graph, print, and punct are needed, so identify them. */ static const char posix_names[] = STRING_alpha0 STRING_lower0 STRING_upper0 STRING_alnum0 STRING_ascii0 STRING_blank0 STRING_cntrl0 STRING_digit0 STRING_graph0 STRING_print0 STRING_punct0 STRING_space0 STRING_word0 STRING_xdigit; static const pcre_uint8 posix_name_lengths[] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 }; #define PC_GRAPH 8 #define PC_PRINT 9 #define PC_PUNCT 10 /* Table of class bit maps for each POSIX class. Each class is formed from a base map, with an optional addition or removal of another map. Then, for some classes, there is some additional tweaking: for [:blank:] the vertical space characters are removed, and for [:alpha:] and [:alnum:] the underscore character is removed. The triples in the table consist of the base map offset, second map offset or -1 if no second map, and a non-negative value for map addition or a negative value for map subtraction (if there are two maps). The absolute value of the third field has these meanings: 0 => no tweaking, 1 => remove vertical space characters, 2 => remove underscore. */ static const int posix_class_maps[] = { cbit_word, cbit_digit, -2, /* alpha */ cbit_lower, -1, 0, /* lower */ cbit_upper, -1, 0, /* upper */ cbit_word, -1, 2, /* alnum - word without underscore */ cbit_print, cbit_cntrl, 0, /* ascii */ cbit_space, -1, 1, /* blank - a GNU extension */ cbit_cntrl, -1, 0, /* cntrl */ cbit_digit, -1, 0, /* digit */ cbit_graph, -1, 0, /* graph */ cbit_print, -1, 0, /* print */ cbit_punct, -1, 0, /* punct */ cbit_space, -1, 0, /* space */ cbit_word, -1, 0, /* word - a Perl extension */ cbit_xdigit,-1, 0 /* xdigit */ }; /* Table of substitutes for \d etc when PCRE_UCP is set. They are replaced by Unicode property escapes. */ #ifdef SUPPORT_UCP static const pcre_uchar string_PNd[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_pNd[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_PXsp[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_pXsp[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_PXwd[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_pXwd[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar *substitutes[] = { string_PNd, /* \D */ string_pNd, /* \d */ string_PXsp, /* \S */ /* Xsp is Perl space, but from 8.34, Perl */ string_pXsp, /* \s */ /* space and POSIX space are the same. */ string_PXwd, /* \W */ string_pXwd /* \w */ }; /* The POSIX class substitutes must be in the order of the POSIX class names, defined above, and there are both positive and negative cases. NULL means no general substitute of a Unicode property escape (\p or \P). However, for some POSIX classes (e.g. graph, print, punct) a special property code is compiled directly. */ static const pcre_uchar string_pL[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_pLl[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_pLu[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_pXan[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_h[] = { CHAR_BACKSLASH, CHAR_h, '\0' }; static const pcre_uchar string_pXps[] = { CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_PL[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_PLl[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_PLu[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_PXan[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar string_H[] = { CHAR_BACKSLASH, CHAR_H, '\0' }; static const pcre_uchar string_PXps[] = { CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' }; static const pcre_uchar *posix_substitutes[] = { string_pL, /* alpha */ string_pLl, /* lower */ string_pLu, /* upper */ string_pXan, /* alnum */ NULL, /* ascii */ string_h, /* blank */ NULL, /* cntrl */ string_pNd, /* digit */ NULL, /* graph */ NULL, /* print */ NULL, /* punct */ string_pXps, /* space */ /* Xps is POSIX space, but from 8.34 */ string_pXwd, /* word */ /* Perl and POSIX space are the same */ NULL, /* xdigit */ /* Negated cases */ string_PL, /* ^alpha */ string_PLl, /* ^lower */ string_PLu, /* ^upper */ string_PXan, /* ^alnum */ NULL, /* ^ascii */ string_H, /* ^blank */ NULL, /* ^cntrl */ string_PNd, /* ^digit */ NULL, /* ^graph */ NULL, /* ^print */ NULL, /* ^punct */ string_PXps, /* ^space */ /* Xps is POSIX space, but from 8.34 */ string_PXwd, /* ^word */ /* Perl and POSIX space are the same */ NULL /* ^xdigit */ }; #define POSIX_SUBSIZE (sizeof(posix_substitutes) / sizeof(pcre_uchar *)) #endif #define STRING(a) # a #define XSTRING(s) STRING(s) /* The texts of compile-time error messages. These are "char *" because they are passed to the outside world. Do not ever re-use any error number, because they are documented. Always add a new error instead. Messages marked DEAD below are no longer used. This used to be a table of strings, but in order to reduce the number of relocations needed when a shared library is loaded dynamically, it is now one long string. We cannot use a table of offsets, because the lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we simply count through to the one we want - this isn't a performance issue because these strings are used only when there is a compilation error. Each substring ends with \0 to insert a null character. This includes the final substring, so that the whole string ends with \0\0, which can be detected when counting through. */ static const char error_texts[] = "no error\0" "\\ at end of pattern\0" "\\c at end of pattern\0" "unrecognized character follows \\\0" "numbers out of order in {} quantifier\0" /* 5 */ "number too big in {} quantifier\0" "missing terminating ] for character class\0" "invalid escape sequence in character class\0" "range out of order in character class\0" "nothing to repeat\0" /* 10 */ "internal error: invalid forward reference offset\0" "internal error: unexpected repeat\0" "unrecognized character after (? or (?-\0" "POSIX named classes are supported only within a class\0" "missing )\0" /* 15 */ "reference to non-existent subpattern\0" "erroffset passed as NULL\0" "unknown option bit(s) set\0" "missing ) after comment\0" "parentheses nested too deeply\0" /** DEAD **/ /* 20 */ "regular expression is too large\0" "failed to get memory\0" "unmatched parentheses\0" "internal error: code overflow\0" "unrecognized character after (?<\0" /* 25 */ "lookbehind assertion is not fixed length\0" "malformed number or name after (?(\0" "conditional group contains more than two branches\0" "assertion expected after (?( or (?(?C)\0" "(?R or (?[+-]digits must be followed by )\0" /* 30 */ "unknown POSIX class name\0" "POSIX collating elements are not supported\0" "this version of PCRE is compiled without UTF support\0" "spare error\0" /** DEAD **/ "character value in \\x{} or \\o{} is too large\0" /* 35 */ "invalid condition (?(0)\0" "\\C not allowed in lookbehind assertion\0" "PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0" "number after (?C is > 255\0" "closing ) for (?C expected\0" /* 40 */ "recursive call could loop indefinitely\0" "unrecognized character after (?P\0" "syntax error in subpattern name (missing terminator)\0" "two named subpatterns have the same name\0" "invalid UTF-8 string\0" /* 45 */ "support for \\P, \\p, and \\X has not been compiled\0" "malformed \\P or \\p sequence\0" "unknown property name after \\P or \\p\0" "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)\0" "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0" /* 50 */ "repeated subpattern is too long\0" /** DEAD **/ "octal value is greater than \\377 in 8-bit non-UTF-8 mode\0" "internal error: overran compiling workspace\0" "internal error: previously-checked referenced subpattern not found\0" "DEFINE group contains more than one branch\0" /* 55 */ "repeating a DEFINE group is not allowed\0" /** DEAD **/ "inconsistent NEWLINE options\0" "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0" "a numbered reference must not be zero\0" "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0" /* 60 */ "(*VERB) not recognized or malformed\0" "number is too big\0" "subpattern name expected\0" "digit expected after (?+\0" "] is an invalid data character in JavaScript compatibility mode\0" /* 65 */ "different names for subpatterns of the same number are not allowed\0" "(*MARK) must have an argument\0" "this version of PCRE is not compiled with Unicode property support\0" #ifndef EBCDIC "\\c must be followed by an ASCII character\0" #else "\\c must be followed by a letter or one of [\\]^_?\0" #endif "\\k is not followed by a braced, angle-bracketed, or quoted name\0" /* 70 */ "internal error: unknown opcode in find_fixedlength()\0" "\\N is not supported in a class\0" "too many forward references\0" "disallowed Unicode code point (>= 0xd800 && <= 0xdfff)\0" "invalid UTF-16 string\0" /* 75 */ "name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)\0" "character value in \\u.... sequence is too large\0" "invalid UTF-32 string\0" "setting UTF is disabled by the application\0" "non-hex character in \\x{} (closing brace missing?)\0" /* 80 */ "non-octal character in \\o{} (closing brace missing?)\0" "missing opening brace after \\o\0" "parentheses are too deeply nested\0" "invalid range in character class\0" "group name must start with a non-digit\0" /* 85 */ "parentheses are too deeply nested (stack check)\0" "digits missing in \\x{} or \\o{}\0" "regular expression is too complicated\0" ; /* Table to identify digits and hex digits. This is used when compiling patterns. Note that the tables in chartables are dependent on the locale, and may mark arbitrary characters as digits - but the PCRE compiling code expects to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have a private table here. It costs 256 bytes, but it is a lot faster than doing character value tests (at least in some simple cases I timed), and in some applications one wants PCRE to compile efficiently as well as match efficiently. For convenience, we use the same bit definitions as in chartables: 0x04 decimal digit 0x08 hexadecimal digit Then we can use ctype_digit and ctype_xdigit in the code. */ /* Using a simple comparison for decimal numbers rather than a memory read is much faster, and the resulting code is simpler (the compiler turns it into a subtraction and unsigned comparison). */ #define IS_DIGIT(x) ((x) >= CHAR_0 && (x) <= CHAR_9) #ifndef EBCDIC /* This is the "normal" case, for ASCII systems, and EBCDIC systems running in UTF-8 mode. */ static const pcre_uint8 digitab[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 */ 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* @ - G */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H - O */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* P - W */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* X - _ */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* ` - g */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h - o */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* p - w */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* x -127 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ #else /* This is the "abnormal" case, for EBCDIC systems not running in UTF-8 mode. */ static const pcre_uint8 digitab[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 10 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 32- 39 20 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 30 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 40 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 72- | */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 50 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 88- 95 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 60 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ? */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g 80 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p 90 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x A0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 B0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* { - G C0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* } - P D0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* \ - X E0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 F0 */ 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ static const pcre_uint8 ebcdic_chartab[] = { /* chartable partial dup */ 0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 0- 7 */ 0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 16- 23 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 32- 39 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 */ 0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /* 72- | */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 */ 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /* 88- 95 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 */ 0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ? */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 */ 0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* { - G */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* } - P */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* \ - X */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ #endif /* This table is used to check whether auto-possessification is possible between adjacent character-type opcodes. The left-hand (repeated) opcode is used to select the row, and the right-hand opcode is use to select the column. A value of 1 means that auto-possessification is OK. For example, the second value in the first row means that \D+\d can be turned into \D++\d. The Unicode property types (\P and \p) have to be present to fill out the table because of what their opcode values are, but the table values should always be zero because property types are handled separately in the code. The last four columns apply to items that cannot be repeated, so there is no need to have rows for them. Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* set. When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */ #define APTROWS (LAST_AUTOTAB_LEFT_OP - FIRST_AUTOTAB_OP + 1) #define APTCOLS (LAST_AUTOTAB_RIGHT_OP - FIRST_AUTOTAB_OP + 1) static const pcre_uint8 autoposstab[APTROWS][APTCOLS] = { /* \D \d \S \s \W \w . .+ \C \P \p \R \H \h \V \v \X \Z \z $ $M */ { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \D */ { 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \d */ { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \S */ { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \s */ { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \W */ { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \w */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* . */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* .+ */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \C */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* \P */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* \p */ { 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }, /* \R */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }, /* \H */ { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, /* \h */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 }, /* \V */ { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0 }, /* \v */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 } /* \X */ }; /* This table is used to check whether auto-possessification is possible between adjacent Unicode property opcodes (OP_PROP and OP_NOTPROP). The left-hand (repeated) opcode is used to select the row, and the right-hand opcode is used to select the column. The values are as follows: 0 Always return FALSE (never auto-possessify) 1 Character groups are distinct (possessify if both are OP_PROP) 2 Check character categories in the same group (general or particular) 3 TRUE if the two opcodes are not the same (PROP vs NOTPROP) 4 Check left general category vs right particular category 5 Check right general category vs left particular category 6 Left alphanum vs right general category 7 Left space vs right general category 8 Left word vs right general category 9 Right alphanum vs left general category 10 Right space vs left general category 11 Right word vs left general category 12 Left alphanum vs right particular category 13 Left space vs right particular category 14 Left word vs right particular category 15 Right alphanum vs left particular category 16 Right space vs left particular category 17 Right word vs left particular category */ static const pcre_uint8 propposstab[PT_TABSIZE][PT_TABSIZE] = { /* ANY LAMP GC PC SC ALNUM SPACE PXSPACE WORD CLIST UCNC */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* PT_ANY */ { 0, 3, 0, 0, 0, 3, 1, 1, 0, 0, 0 }, /* PT_LAMP */ { 0, 0, 2, 4, 0, 9, 10, 10, 11, 0, 0 }, /* PT_GC */ { 0, 0, 5, 2, 0, 15, 16, 16, 17, 0, 0 }, /* PT_PC */ { 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0 }, /* PT_SC */ { 0, 3, 6, 12, 0, 3, 1, 1, 0, 0, 0 }, /* PT_ALNUM */ { 0, 1, 7, 13, 0, 1, 3, 3, 1, 0, 0 }, /* PT_SPACE */ { 0, 1, 7, 13, 0, 1, 3, 3, 1, 0, 0 }, /* PT_PXSPACE */ { 0, 0, 8, 14, 0, 0, 1, 1, 3, 0, 0 }, /* PT_WORD */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* PT_CLIST */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3 } /* PT_UCNC */ }; /* This table is used to check whether auto-possessification is possible between adjacent Unicode property opcodes (OP_PROP and OP_NOTPROP) when one specifies a general category and the other specifies a particular category. The row is selected by the general category and the column by the particular category. The value is 1 if the particular category is not part of the general category. */ static const pcre_uint8 catposstab[7][30] = { /* Cc Cf Cn Co Cs Ll Lm Lo Lt Lu Mc Me Mn Nd Nl No Pc Pd Pe Pf Pi Po Ps Sc Sk Sm So Zl Zp Zs */ { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* C */ { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* L */ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* M */ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* N */ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 }, /* P */ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }, /* S */ { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 } /* Z */ }; /* This table is used when checking ALNUM, (PX)SPACE, SPACE, and WORD against a general or particular category. The properties in each row are those that apply to the character set in question. Duplication means that a little unnecessary work is done when checking, but this keeps things much simpler because they can all use the same code. For more details see the comment where this table is used. Note: SPACE and PXSPACE used to be different because Perl excluded VT from "space", but from Perl 5.18 it's included, so both categories are treated the same here. */ static const pcre_uint8 posspropstab[3][4] = { { ucp_L, ucp_N, ucp_N, ucp_Nl }, /* ALNUM, 3rd and 4th values redundant */ { ucp_Z, ucp_Z, ucp_C, ucp_Cc }, /* SPACE and PXSPACE, 2nd value redundant */ { ucp_L, ucp_N, ucp_P, ucp_Po } /* WORD */ }; /* This table is used when converting repeating opcodes into possessified versions as a result of an explicit possessive quantifier such as ++. A zero value means there is no possessified version - in those cases the item in question must be wrapped in ONCE brackets. The table is truncated at OP_CALLOUT because all relevant opcodes are less than that. */ static const pcre_uint8 opcode_possessify[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 15 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 - 31 */ 0, /* NOTI */ OP_POSSTAR, 0, /* STAR, MINSTAR */ OP_POSPLUS, 0, /* PLUS, MINPLUS */ OP_POSQUERY, 0, /* QUERY, MINQUERY */ OP_POSUPTO, 0, /* UPTO, MINUPTO */ 0, /* EXACT */ 0, 0, 0, 0, /* POS{STAR,PLUS,QUERY,UPTO} */ OP_POSSTARI, 0, /* STARI, MINSTARI */ OP_POSPLUSI, 0, /* PLUSI, MINPLUSI */ OP_POSQUERYI, 0, /* QUERYI, MINQUERYI */ OP_POSUPTOI, 0, /* UPTOI, MINUPTOI */ 0, /* EXACTI */ 0, 0, 0, 0, /* POS{STARI,PLUSI,QUERYI,UPTOI} */ OP_NOTPOSSTAR, 0, /* NOTSTAR, NOTMINSTAR */ OP_NOTPOSPLUS, 0, /* NOTPLUS, NOTMINPLUS */ OP_NOTPOSQUERY, 0, /* NOTQUERY, NOTMINQUERY */ OP_NOTPOSUPTO, 0, /* NOTUPTO, NOTMINUPTO */ 0, /* NOTEXACT */ 0, 0, 0, 0, /* NOTPOS{STAR,PLUS,QUERY,UPTO} */ OP_NOTPOSSTARI, 0, /* NOTSTARI, NOTMINSTARI */ OP_NOTPOSPLUSI, 0, /* NOTPLUSI, NOTMINPLUSI */ OP_NOTPOSQUERYI, 0, /* NOTQUERYI, NOTMINQUERYI */ OP_NOTPOSUPTOI, 0, /* NOTUPTOI, NOTMINUPTOI */ 0, /* NOTEXACTI */ 0, 0, 0, 0, /* NOTPOS{STARI,PLUSI,QUERYI,UPTOI} */ OP_TYPEPOSSTAR, 0, /* TYPESTAR, TYPEMINSTAR */ OP_TYPEPOSPLUS, 0, /* TYPEPLUS, TYPEMINPLUS */ OP_TYPEPOSQUERY, 0, /* TYPEQUERY, TYPEMINQUERY */ OP_TYPEPOSUPTO, 0, /* TYPEUPTO, TYPEMINUPTO */ 0, /* TYPEEXACT */ 0, 0, 0, 0, /* TYPEPOS{STAR,PLUS,QUERY,UPTO} */ OP_CRPOSSTAR, 0, /* CRSTAR, CRMINSTAR */ OP_CRPOSPLUS, 0, /* CRPLUS, CRMINPLUS */ OP_CRPOSQUERY, 0, /* CRQUERY, CRMINQUERY */ OP_CRPOSRANGE, 0, /* CRRANGE, CRMINRANGE */ 0, 0, 0, 0, /* CRPOS{STAR,PLUS,QUERY,RANGE} */ 0, 0, 0, /* CLASS, NCLASS, XCLASS */ 0, 0, /* REF, REFI */ 0, 0, /* DNREF, DNREFI */ 0, 0 /* RECURSE, CALLOUT */ }; /************************************************* * Find an error text * *************************************************/ /* The error texts are now all in one long string, to save on relocations. As some of the text is of unknown length, we can't use a table of offsets. Instead, just count through the strings. This is not a performance issue because it happens only when there has been a compilation error. Argument: the error number Returns: pointer to the error string */ static const char * find_error_text(int n) { const char *s = error_texts; for (; n > 0; n--) { while (*s++ != CHAR_NULL) {}; if (*s == CHAR_NULL) return "Error text not found (please report)"; } return s; } /************************************************* * Expand the workspace * *************************************************/ /* This function is called during the second compiling phase, if the number of forward references fills the existing workspace, which is originally a block on the stack. A larger block is obtained from malloc() unless the ultimate limit has been reached or the increase will be rather small. Argument: pointer to the compile data block Returns: 0 if all went well, else an error number */ static int expand_workspace(compile_data *cd) { pcre_uchar *newspace; int newsize = cd->workspace_size * 2; if (newsize > COMPILE_WORK_SIZE_MAX) newsize = COMPILE_WORK_SIZE_MAX; if (cd->workspace_size >= COMPILE_WORK_SIZE_MAX || newsize - cd->workspace_size < WORK_SIZE_SAFETY_MARGIN) return ERR72; newspace = (PUBL(malloc))(IN_UCHARS(newsize)); if (newspace == NULL) return ERR21; memcpy(newspace, cd->start_workspace, cd->workspace_size * sizeof(pcre_uchar)); cd->hwm = (pcre_uchar *)newspace + (cd->hwm - cd->start_workspace); if (cd->workspace_size > COMPILE_WORK_SIZE) (PUBL(free))((void *)cd->start_workspace); cd->start_workspace = newspace; cd->workspace_size = newsize; return 0; } /************************************************* * Check for counted repeat * *************************************************/ /* This function is called when a '{' is encountered in a place where it might start a quantifier. It looks ahead to see if it really is a quantifier or not. It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd} where the ddds are digits. Arguments: p pointer to the first char after '{' Returns: TRUE or FALSE */ static BOOL is_counted_repeat(const pcre_uchar *p) { if (!IS_DIGIT(*p)) return FALSE; p++; while (IS_DIGIT(*p)) p++; if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE; if (*p++ != CHAR_COMMA) return FALSE; if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE; if (!IS_DIGIT(*p)) return FALSE; p++; while (IS_DIGIT(*p)) p++; return (*p == CHAR_RIGHT_CURLY_BRACKET); } /************************************************* * Handle escapes * *************************************************/ /* This function is called when a \ has been encountered. It either returns a positive value for a simple escape such as \n, or 0 for a data character which will be placed in chptr. A backreference to group n is returned as negative n. When UTF-8 is enabled, a positive value greater than 255 may be returned in chptr. On entry, ptr is pointing at the \. On exit, it is on the final character of the escape sequence. Arguments: ptrptr points to the pattern position pointer chptr points to a returned data character errorcodeptr points to the errorcode variable bracount number of previous extracting brackets options the options bits isclass TRUE if inside a character class Returns: zero => a data character positive => a special escape sequence negative => a back reference on error, errorcodeptr is set */ static int check_escape(const pcre_uchar **ptrptr, pcre_uint32 *chptr, int *errorcodeptr, int bracount, int options, BOOL isclass) { /* PCRE_UTF16 has the same value as PCRE_UTF8. */ BOOL utf = (options & PCRE_UTF8) != 0; const pcre_uchar *ptr = *ptrptr + 1; pcre_uint32 c; int escape = 0; int i; GETCHARINCTEST(c, ptr); /* Get character value, increment pointer */ ptr--; /* Set pointer back to the last byte */ /* If backslash is at the end of the pattern, it's an error. */ if (c == CHAR_NULL) *errorcodeptr = ERR1; /* Non-alphanumerics are literals. For digits or letters, do an initial lookup in a table. A non-zero result is something that can be returned immediately. Otherwise further processing may be required. */ #ifndef EBCDIC /* ASCII/UTF-8 coding */ /* Not alphanumeric */ else if (c < CHAR_0 || c > CHAR_z) {} else if ((i = escapes[c - CHAR_0]) != 0) { if (i > 0) c = (pcre_uint32)i; else escape = -i; } #else /* EBCDIC coding */ /* Not alphanumeric */ else if (c < CHAR_a || (!MAX_255(c) || (ebcdic_chartab[c] & 0x0E) == 0)) {} else if ((i = escapes[c - 0x48]) != 0) { if (i > 0) c = (pcre_uint32)i; else escape = -i; } #endif /* Escapes that need further processing, or are illegal. */ else { const pcre_uchar *oldptr; BOOL braced, negated, overflow; int s; switch (c) { /* A number of Perl escapes are not handled by PCRE. We give an explicit error. */ case CHAR_l: case CHAR_L: *errorcodeptr = ERR37; break; case CHAR_u: if ((options & PCRE_JAVASCRIPT_COMPAT) != 0) { /* In JavaScript, \u must be followed by four hexadecimal numbers. Otherwise it is a lowercase u letter. */ if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0 && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0 && MAX_255(ptr[3]) && (digitab[ptr[3]] & ctype_xdigit) != 0 && MAX_255(ptr[4]) && (digitab[ptr[4]] & ctype_xdigit) != 0) { c = 0; for (i = 0; i < 4; ++i) { register pcre_uint32 cc = *(++ptr); #ifndef EBCDIC /* ASCII/UTF-8 coding */ if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); #else /* EBCDIC coding */ if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); #endif } #if defined COMPILE_PCRE8 if (c > (utf ? 0x10ffffU : 0xffU)) #elif defined COMPILE_PCRE16 if (c > (utf ? 0x10ffffU : 0xffffU)) #elif defined COMPILE_PCRE32 if (utf && c > 0x10ffffU) #endif { *errorcodeptr = ERR76; } else if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; } } else *errorcodeptr = ERR37; break; case CHAR_U: /* In JavaScript, \U is an uppercase U letter. */ if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) *errorcodeptr = ERR37; break; /* In a character class, \g is just a literal "g". Outside a character class, \g must be followed by one of a number of specific things: (1) A number, either plain or braced. If positive, it is an absolute backreference. If negative, it is a relative backreference. This is a Perl 5.10 feature. (2) Perl 5.10 also supports \g{name} as a reference to a named group. This is part of Perl's movement towards a unified syntax for back references. As this is synonymous with \k{name}, we fudge it up by pretending it really was \k. (3) For Oniguruma compatibility we also support \g followed by a name or a number either in angle brackets or in single quotes. However, these are (possibly recursive) subroutine calls, _not_ backreferences. Just return the ESC_g code (cf \k). */ case CHAR_g: if (isclass) break; if (ptr[1] == CHAR_LESS_THAN_SIGN || ptr[1] == CHAR_APOSTROPHE) { escape = ESC_g; break; } /* Handle the Perl-compatible cases */ if (ptr[1] == CHAR_LEFT_CURLY_BRACKET) { const pcre_uchar *p; for (p = ptr+2; *p != CHAR_NULL && *p != CHAR_RIGHT_CURLY_BRACKET; p++) if (*p != CHAR_MINUS && !IS_DIGIT(*p)) break; if (*p != CHAR_NULL && *p != CHAR_RIGHT_CURLY_BRACKET) { escape = ESC_k; break; } braced = TRUE; ptr++; } else braced = FALSE; if (ptr[1] == CHAR_MINUS) { negated = TRUE; ptr++; } else negated = FALSE; /* The integer range is limited by the machine's int representation. */ s = 0; overflow = FALSE; while (IS_DIGIT(ptr[1])) { if (s > INT_MAX / 10 - 1) /* Integer overflow */ { overflow = TRUE; break; } s = s * 10 + (int)(*(++ptr) - CHAR_0); } if (overflow) /* Integer overflow */ { while (IS_DIGIT(ptr[1])) ptr++; *errorcodeptr = ERR61; break; } if (braced && *(++ptr) != CHAR_RIGHT_CURLY_BRACKET) { *errorcodeptr = ERR57; break; } if (s == 0) { *errorcodeptr = ERR58; break; } if (negated) { if (s > bracount) { *errorcodeptr = ERR15; break; } s = bracount - (s - 1); } escape = -s; break; /* The handling of escape sequences consisting of a string of digits starting with one that is not zero is not straightforward. Perl has changed over the years. Nowadays \g{} for backreferences and \o{} for octal are recommended to avoid the ambiguities in the old syntax. Outside a character class, the digits are read as a decimal number. If the number is less than 8 (used to be 10), or if there are that many previous extracting left brackets, then it is a back reference. Otherwise, up to three octal digits are read to form an escaped byte. Thus \123 is likely to be octal 123 (cf \0123, which is octal 012 followed by the literal 3). If the octal value is greater than 377, the least significant 8 bits are taken. \8 and \9 are treated as the literal characters 8 and 9. Inside a character class, \ followed by a digit is always either a literal 8 or 9 or an octal number. */ case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: case CHAR_5: case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9: if (!isclass) { oldptr = ptr; /* The integer range is limited by the machine's int representation. */ s = (int)(c -CHAR_0); overflow = FALSE; while (IS_DIGIT(ptr[1])) { if (s > INT_MAX / 10 - 1) /* Integer overflow */ { overflow = TRUE; break; } s = s * 10 + (int)(*(++ptr) - CHAR_0); } if (overflow) /* Integer overflow */ { while (IS_DIGIT(ptr[1])) ptr++; *errorcodeptr = ERR61; break; } if (s < 8 || s <= bracount) /* Check for back reference */ { escape = -s; break; } ptr = oldptr; /* Put the pointer back and fall through */ } /* Handle a digit following \ when the number is not a back reference. If the first digit is 8 or 9, Perl used to generate a binary zero byte and then treat the digit as a following literal. At least by Perl 5.18 this changed so as not to insert the binary zero. */ if ((c = *ptr) >= CHAR_8) break; /* Fall through with a digit less than 8 */ /* \0 always starts an octal number, but we may drop through to here with a larger first octal digit. The original code used just to take the least significant 8 bits of octal numbers (I think this is what early Perls used to do). Nowadays we allow for larger numbers in UTF-8 mode and 16-bit mode, but no more than 3 octal digits. */ case CHAR_0: c -= CHAR_0; while(i++ < 2 && ptr[1] >= CHAR_0 && ptr[1] <= CHAR_7) c = c * 8 + *(++ptr) - CHAR_0; #ifdef COMPILE_PCRE8 if (!utf && c > 0xff) *errorcodeptr = ERR51; #endif break; /* \o is a relatively new Perl feature, supporting a more general way of specifying character codes in octal. The only supported form is \o{ddd}. */ case CHAR_o: if (ptr[1] != CHAR_LEFT_CURLY_BRACKET) *errorcodeptr = ERR81; else if (ptr[2] == CHAR_RIGHT_CURLY_BRACKET) *errorcodeptr = ERR86; else { ptr += 2; c = 0; overflow = FALSE; while (*ptr >= CHAR_0 && *ptr <= CHAR_7) { register pcre_uint32 cc = *ptr++; if (c == 0 && cc == CHAR_0) continue; /* Leading zeroes */ #ifdef COMPILE_PCRE32 if (c >= 0x20000000l) { overflow = TRUE; break; } #endif c = (c << 3) + cc - CHAR_0 ; #if defined COMPILE_PCRE8 if (c > (utf ? 0x10ffffU : 0xffU)) { overflow = TRUE; break; } #elif defined COMPILE_PCRE16 if (c > (utf ? 0x10ffffU : 0xffffU)) { overflow = TRUE; break; } #elif defined COMPILE_PCRE32 if (utf && c > 0x10ffffU) { overflow = TRUE; break; } #endif } if (overflow) { while (*ptr >= CHAR_0 && *ptr <= CHAR_7) ptr++; *errorcodeptr = ERR34; } else if (*ptr == CHAR_RIGHT_CURLY_BRACKET) { if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; } else *errorcodeptr = ERR80; } break; /* \x is complicated. In JavaScript, \x must be followed by two hexadecimal numbers. Otherwise it is a lowercase x letter. */ case CHAR_x: if ((options & PCRE_JAVASCRIPT_COMPAT) != 0) { if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0 && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0) { c = 0; for (i = 0; i < 2; ++i) { register pcre_uint32 cc = *(++ptr); #ifndef EBCDIC /* ASCII/UTF-8 coding */ if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); #else /* EBCDIC coding */ if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); #endif } } } /* End JavaScript handling */ /* Handle \x in Perl's style. \x{ddd} is a character number which can be greater than 0xff in utf or non-8bit mode, but only if the ddd are hex digits. If not, { used to be treated as a data character. However, Perl seems to read hex digits up to the first non-such, and ignore the rest, so that, for example \x{zz} matches a binary zero. This seems crazy, so PCRE now gives an error. */ else { if (ptr[1] == CHAR_LEFT_CURLY_BRACKET) { ptr += 2; if (*ptr == CHAR_RIGHT_CURLY_BRACKET) { *errorcodeptr = ERR86; break; } c = 0; overflow = FALSE; while (MAX_255(*ptr) && (digitab[*ptr] & ctype_xdigit) != 0) { register pcre_uint32 cc = *ptr++; if (c == 0 && cc == CHAR_0) continue; /* Leading zeroes */ #ifdef COMPILE_PCRE32 if (c >= 0x10000000l) { overflow = TRUE; break; } #endif #ifndef EBCDIC /* ASCII/UTF-8 coding */ if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); #else /* EBCDIC coding */ if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); #endif #if defined COMPILE_PCRE8 if (c > (utf ? 0x10ffffU : 0xffU)) { overflow = TRUE; break; } #elif defined COMPILE_PCRE16 if (c > (utf ? 0x10ffffU : 0xffffU)) { overflow = TRUE; break; } #elif defined COMPILE_PCRE32 if (utf && c > 0x10ffffU) { overflow = TRUE; break; } #endif } if (overflow) { while (MAX_255(*ptr) && (digitab[*ptr] & ctype_xdigit) != 0) ptr++; *errorcodeptr = ERR34; } else if (*ptr == CHAR_RIGHT_CURLY_BRACKET) { if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; } /* If the sequence of hex digits does not end with '}', give an error. We used just to recognize this construct and fall through to the normal \x handling, but nowadays Perl gives an error, which seems much more sensible, so we do too. */ else *errorcodeptr = ERR79; } /* End of \x{} processing */ /* Read a single-byte hex-defined char (up to two hex digits after \x) */ else { c = 0; while (i++ < 2 && MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0) { pcre_uint32 cc; /* Some compilers don't like */ cc = *(++ptr); /* ++ in initializers */ #ifndef EBCDIC /* ASCII/UTF-8 coding */ if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ c = c * 16 + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); #else /* EBCDIC coding */ if (cc <= CHAR_z) cc += 64; /* Convert to upper case */ c = c * 16 + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); #endif } } /* End of \xdd handling */ } /* End of Perl-style \x handling */ break; /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped. An error is given if the byte following \c is not an ASCII character. This coding is ASCII-specific, but then the whole concept of \cx is ASCII-specific. (However, an EBCDIC equivalent has now been added.) */ case CHAR_c: c = *(++ptr); if (c == CHAR_NULL) { *errorcodeptr = ERR2; break; } #ifndef EBCDIC /* ASCII/UTF-8 coding */ if (c > 127) /* Excludes all non-ASCII in either mode */ { *errorcodeptr = ERR68; break; } if (c >= CHAR_a && c <= CHAR_z) c -= 32; c ^= 0x40; #else /* EBCDIC coding */ if (c >= CHAR_a && c <= CHAR_z) c += 64; if (c == CHAR_QUESTION_MARK) c = ('\\' == 188 && '`' == 74)? 0x5f : 0xff; else { for (i = 0; i < 32; i++) { if (c == ebcdic_escape_c[i]) break; } if (i < 32) c = i; else *errorcodeptr = ERR68; } #endif break; /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any other alphanumeric following \ is an error if PCRE_EXTRA was set; otherwise, for Perl compatibility, it is a literal. This code looks a bit odd, but there used to be some cases other than the default, and there may be again in future, so I haven't "optimized" it. */ default: if ((options & PCRE_EXTRA) != 0) switch(c) { default: *errorcodeptr = ERR3; break; } break; } } /* Perl supports \N{name} for character names, as well as plain \N for "not newline". PCRE does not support \N{name}. However, it does support quantification such as \N{2,3}. */ if (escape == ESC_N && ptr[1] == CHAR_LEFT_CURLY_BRACKET && !is_counted_repeat(ptr+2)) *errorcodeptr = ERR37; /* If PCRE_UCP is set, we change the values for \d etc. */ if ((options & PCRE_UCP) != 0 && escape >= ESC_D && escape <= ESC_w) escape += (ESC_DU - ESC_D); /* Set the pointer to the final character before returning. */ *ptrptr = ptr; *chptr = c; return escape; } #ifdef SUPPORT_UCP /************************************************* * Handle \P and \p * *************************************************/ /* This function is called after \P or \p has been encountered, provided that PCRE is compiled with support for Unicode properties. On entry, ptrptr is pointing at the P or p. On exit, it is pointing at the final character of the escape sequence. Argument: ptrptr points to the pattern position pointer negptr points to a boolean that is set TRUE for negation else FALSE ptypeptr points to an unsigned int that is set to the type value pdataptr points to an unsigned int that is set to the detailed property value errorcodeptr points to the error code variable Returns: TRUE if the type value was found, or FALSE for an invalid type */ static BOOL get_ucp(const pcre_uchar **ptrptr, BOOL *negptr, unsigned int *ptypeptr, unsigned int *pdataptr, int *errorcodeptr) { pcre_uchar c; int i, bot, top; const pcre_uchar *ptr = *ptrptr; pcre_uchar name[32]; c = *(++ptr); if (c == CHAR_NULL) goto ERROR_RETURN; *negptr = FALSE; /* \P or \p can be followed by a name in {}, optionally preceded by ^ for negation. */ if (c == CHAR_LEFT_CURLY_BRACKET) { if (ptr[1] == CHAR_CIRCUMFLEX_ACCENT) { *negptr = TRUE; ptr++; } for (i = 0; i < (int)(sizeof(name) / sizeof(pcre_uchar)) - 1; i++) { c = *(++ptr); if (c == CHAR_NULL) goto ERROR_RETURN; if (c == CHAR_RIGHT_CURLY_BRACKET) break; name[i] = c; } if (c != CHAR_RIGHT_CURLY_BRACKET) goto ERROR_RETURN; name[i] = 0; } /* Otherwise there is just one following character */ else { name[0] = c; name[1] = 0; } *ptrptr = ptr; /* Search for a recognized property name using binary chop */ bot = 0; top = PRIV(utt_size); while (bot < top) { int r; i = (bot + top) >> 1; r = STRCMP_UC_C8(name, PRIV(utt_names) + PRIV(utt)[i].name_offset); if (r == 0) { *ptypeptr = PRIV(utt)[i].type; *pdataptr = PRIV(utt)[i].value; return TRUE; } if (r > 0) bot = i + 1; else top = i; } *errorcodeptr = ERR47; *ptrptr = ptr; return FALSE; ERROR_RETURN: *errorcodeptr = ERR46; *ptrptr = ptr; return FALSE; } #endif /************************************************* * Read repeat counts * *************************************************/ /* Read an item of the form {n,m} and return the values. This is called only after is_counted_repeat() has confirmed that a repeat-count quantifier exists, so the syntax is guaranteed to be correct, but we need to check the values. Arguments: p pointer to first char after '{' minp pointer to int for min maxp pointer to int for max returned as -1 if no max errorcodeptr points to error code variable Returns: pointer to '}' on success; current ptr on error, with errorcodeptr set non-zero */ static const pcre_uchar * read_repeat_counts(const pcre_uchar *p, int *minp, int *maxp, int *errorcodeptr) { int min = 0; int max = -1; while (IS_DIGIT(*p)) { min = min * 10 + (int)(*p++ - CHAR_0); if (min > 65535) { *errorcodeptr = ERR5; return p; } } if (*p == CHAR_RIGHT_CURLY_BRACKET) max = min; else { if (*(++p) != CHAR_RIGHT_CURLY_BRACKET) { max = 0; while(IS_DIGIT(*p)) { max = max * 10 + (int)(*p++ - CHAR_0); if (max > 65535) { *errorcodeptr = ERR5; return p; } } if (max < min) { *errorcodeptr = ERR4; return p; } } } *minp = min; *maxp = max; return p; } /************************************************* * Find first significant op code * *************************************************/ /* This is called by several functions that scan a compiled expression looking for a fixed first character, or an anchoring op code etc. It skips over things that do not influence this. For some calls, it makes sense to skip negative forward and all backward assertions, and also the \b assertion; for others it does not. Arguments: code pointer to the start of the group skipassert TRUE if certain assertions are to be skipped Returns: pointer to the first significant opcode */ static const pcre_uchar* first_significant_code(const pcre_uchar *code, BOOL skipassert) { for (;;) { switch ((int)*code) { case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: if (!skipassert) return code; do code += GET(code, 1); while (*code == OP_ALT); code += PRIV(OP_lengths)[*code]; break; case OP_WORD_BOUNDARY: case OP_NOT_WORD_BOUNDARY: if (!skipassert) return code; /* Fall through */ case OP_CALLOUT: case OP_CREF: case OP_DNCREF: case OP_RREF: case OP_DNRREF: case OP_DEF: code += PRIV(OP_lengths)[*code]; break; default: return code; } } /* Control never reaches here */ } /************************************************* * Find the fixed length of a branch * *************************************************/ /* Scan a branch and compute the fixed length of subject that will match it, if the length is fixed. This is needed for dealing with backward assertions. In UTF8 mode, the result is in characters rather than bytes. The branch is temporarily terminated with OP_END when this function is called. This function is called when a backward assertion is encountered, so that if it fails, the error message can point to the correct place in the pattern. However, we cannot do this when the assertion contains subroutine calls, because they can be forward references. We solve this by remembering this case and doing the check at the end; a flag specifies which mode we are running in. Arguments: code points to the start of the pattern (the bracket) utf TRUE in UTF-8 / UTF-16 / UTF-32 mode atend TRUE if called when the pattern is complete cd the "compile data" structure recurses chain of recurse_check to catch mutual recursion Returns: the fixed length, or -1 if there is no fixed length, or -2 if \C was encountered (in UTF-8 mode only) or -3 if an OP_RECURSE item was encountered and atend is FALSE or -4 if an unknown opcode was encountered (internal error) */ static int find_fixedlength(pcre_uchar *code, BOOL utf, BOOL atend, compile_data *cd, recurse_check *recurses) { int length = -1; recurse_check this_recurse; register int branchlength = 0; register pcre_uchar *cc = code + 1 + LINK_SIZE; /* Scan along the opcodes for this branch. If we get to the end of the branch, check the length against that of the other branches. */ for (;;) { int d; pcre_uchar *ce, *cs; register pcre_uchar op = *cc; switch (op) { /* We only need to continue for OP_CBRA (normal capturing bracket) and OP_BRA (normal non-capturing bracket) because the other variants of these opcodes are all concerned with unlimited repeated groups, which of course are not of fixed length. */ case OP_CBRA: case OP_BRA: case OP_ONCE: case OP_ONCE_NC: case OP_COND: d = find_fixedlength(cc + ((op == OP_CBRA)? IMM2_SIZE : 0), utf, atend, cd, recurses); if (d < 0) return d; branchlength += d; do cc += GET(cc, 1); while (*cc == OP_ALT); cc += 1 + LINK_SIZE; break; /* Reached end of a branch; if it's a ket it is the end of a nested call. If it's ALT it is an alternation in a nested call. An ACCEPT is effectively an ALT. If it is END it's the end of the outer call. All can be handled by the same code. Note that we must not include the OP_KETRxxx opcodes here, because they all imply an unlimited repeat. */ case OP_ALT: case OP_KET: case OP_END: case OP_ACCEPT: case OP_ASSERT_ACCEPT: if (length < 0) length = branchlength; else if (length != branchlength) return -1; if (*cc != OP_ALT) return length; cc += 1 + LINK_SIZE; branchlength = 0; break; /* A true recursion implies not fixed length, but a subroutine call may be OK. If the subroutine is a forward reference, we can't deal with it until the end of the pattern, so return -3. */ case OP_RECURSE: if (!atend) return -3; cs = ce = (pcre_uchar *)cd->start_code + GET(cc, 1); /* Start subpattern */ do ce += GET(ce, 1); while (*ce == OP_ALT); /* End subpattern */ if (cc > cs && cc < ce) return -1; /* Recursion */ else /* Check for mutual recursion */ { recurse_check *r = recurses; for (r = recurses; r != NULL; r = r->prev) if (r->group == cs) break; if (r != NULL) return -1; /* Mutual recursion */ } this_recurse.prev = recurses; this_recurse.group = cs; d = find_fixedlength(cs + IMM2_SIZE, utf, atend, cd, &this_recurse); if (d < 0) return d; branchlength += d; cc += 1 + LINK_SIZE; break; /* Skip over assertive subpatterns */ case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: do cc += GET(cc, 1); while (*cc == OP_ALT); cc += 1 + LINK_SIZE; break; /* Skip over things that don't match chars */ case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: cc += cc[1] + PRIV(OP_lengths)[*cc]; break; case OP_CALLOUT: case OP_CIRC: case OP_CIRCM: case OP_CLOSE: case OP_COMMIT: case OP_CREF: case OP_DEF: case OP_DNCREF: case OP_DNRREF: case OP_DOLL: case OP_DOLLM: case OP_EOD: case OP_EODN: case OP_FAIL: case OP_NOT_WORD_BOUNDARY: case OP_PRUNE: case OP_REVERSE: case OP_RREF: case OP_SET_SOM: case OP_SKIP: case OP_SOD: case OP_SOM: case OP_THEN: case OP_WORD_BOUNDARY: cc += PRIV(OP_lengths)[*cc]; break; /* Handle literal characters */ case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: branchlength++; cc += 2; #ifdef SUPPORT_UTF if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; /* Handle exact repetitions. The count is already in characters, but we need to skip over a multibyte character in UTF8 mode. */ case OP_EXACT: case OP_EXACTI: case OP_NOTEXACT: case OP_NOTEXACTI: branchlength += (int)GET2(cc,1); cc += 2 + IMM2_SIZE; #ifdef SUPPORT_UTF if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; case OP_TYPEEXACT: branchlength += GET2(cc,1); if (cc[1 + IMM2_SIZE] == OP_PROP || cc[1 + IMM2_SIZE] == OP_NOTPROP) cc += 2; cc += 1 + IMM2_SIZE + 1; break; /* Handle single-char matchers */ case OP_PROP: case OP_NOTPROP: cc += 2; /* Fall through */ case OP_HSPACE: case OP_VSPACE: case OP_NOT_HSPACE: case OP_NOT_VSPACE: case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: case OP_ALLANY: branchlength++; cc++; break; /* The single-byte matcher isn't allowed. This only happens in UTF-8 mode; otherwise \C is coded as OP_ALLANY. */ case OP_ANYBYTE: return -2; /* Check a class for variable quantification */ case OP_CLASS: case OP_NCLASS: #if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 case OP_XCLASS: /* The original code caused an unsigned overflow in 64 bit systems, so now we use a conditional statement. */ if (op == OP_XCLASS) cc += GET(cc, 1); else cc += PRIV(OP_lengths)[OP_CLASS]; #else cc += PRIV(OP_lengths)[OP_CLASS]; #endif switch (*cc) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSSTAR: case OP_CRPOSPLUS: case OP_CRPOSQUERY: return -1; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: if (GET2(cc,1) != GET2(cc,1+IMM2_SIZE)) return -1; branchlength += (int)GET2(cc,1); cc += 1 + 2 * IMM2_SIZE; break; default: branchlength++; } break; /* Anything else is variable length */ case OP_ANYNL: case OP_BRAMINZERO: case OP_BRAPOS: case OP_BRAPOSZERO: case OP_BRAZERO: case OP_CBRAPOS: case OP_EXTUNI: case OP_KETRMAX: case OP_KETRMIN: case OP_KETRPOS: case OP_MINPLUS: case OP_MINPLUSI: case OP_MINQUERY: case OP_MINQUERYI: case OP_MINSTAR: case OP_MINSTARI: case OP_MINUPTO: case OP_MINUPTOI: case OP_NOTMINPLUS: case OP_NOTMINPLUSI: case OP_NOTMINQUERY: case OP_NOTMINQUERYI: case OP_NOTMINSTAR: case OP_NOTMINSTARI: case OP_NOTMINUPTO: case OP_NOTMINUPTOI: case OP_NOTPLUS: case OP_NOTPLUSI: case OP_NOTPOSPLUS: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERY: case OP_NOTPOSQUERYI: case OP_NOTPOSSTAR: case OP_NOTPOSSTARI: case OP_NOTPOSUPTO: case OP_NOTPOSUPTOI: case OP_NOTQUERY: case OP_NOTQUERYI: case OP_NOTSTAR: case OP_NOTSTARI: case OP_NOTUPTO: case OP_NOTUPTOI: case OP_PLUS: case OP_PLUSI: case OP_POSPLUS: case OP_POSPLUSI: case OP_POSQUERY: case OP_POSQUERYI: case OP_POSSTAR: case OP_POSSTARI: case OP_POSUPTO: case OP_POSUPTOI: case OP_QUERY: case OP_QUERYI: case OP_REF: case OP_REFI: case OP_DNREF: case OP_DNREFI: case OP_SBRA: case OP_SBRAPOS: case OP_SCBRA: case OP_SCBRAPOS: case OP_SCOND: case OP_SKIPZERO: case OP_STAR: case OP_STARI: case OP_TYPEMINPLUS: case OP_TYPEMINQUERY: case OP_TYPEMINSTAR: case OP_TYPEMINUPTO: case OP_TYPEPLUS: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: case OP_TYPEPOSSTAR: case OP_TYPEPOSUPTO: case OP_TYPEQUERY: case OP_TYPESTAR: case OP_TYPEUPTO: case OP_UPTO: case OP_UPTOI: return -1; /* Catch unrecognized opcodes so that when new ones are added they are not forgotten, as has happened in the past. */ default: return -4; } } /* Control never gets here */ } /************************************************* * Scan compiled regex for specific bracket * *************************************************/ /* This little function scans through a compiled pattern until it finds a capturing bracket with the given number, or, if the number is negative, an instance of OP_REVERSE for a lookbehind. The function is global in the C sense so that it can be called from pcre_study() when finding the minimum matching length. Arguments: code points to start of expression utf TRUE in UTF-8 / UTF-16 / UTF-32 mode number the required bracket number or negative to find a lookbehind Returns: pointer to the opcode for the bracket, or NULL if not found */ const pcre_uchar * PRIV(find_bracket)(const pcre_uchar *code, BOOL utf, int number) { for (;;) { register pcre_uchar c = *code; if (c == OP_END) return NULL; /* XCLASS is used for classes that cannot be represented just by a bit map. This includes negated single high-valued characters. The length in the table is zero; the actual length is stored in the compiled code. */ if (c == OP_XCLASS) code += GET(code, 1); /* Handle recursion */ else if (c == OP_REVERSE) { if (number < 0) return (pcre_uchar *)code; code += PRIV(OP_lengths)[c]; } /* Handle capturing bracket */ else if (c == OP_CBRA || c == OP_SCBRA || c == OP_CBRAPOS || c == OP_SCBRAPOS) { int n = (int)GET2(code, 1+LINK_SIZE); if (n == number) return (pcre_uchar *)code; code += PRIV(OP_lengths)[c]; } /* Otherwise, we can get the item's length from the table, except that for repeated character types, we have to test for \p and \P, which have an extra two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we must add in its length. */ else { switch(c) { case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; break; case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSUPTO: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2; break; case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: code += code[1]; break; } /* Add in the fixed length from the table */ code += PRIV(OP_lengths)[c]; /* In UTF-8 mode, opcodes that are followed by a character may be followed by a multi-byte character. The length in the table is a minimum, so we have to arrange to skip the extra bytes. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf) switch(c) { case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_EXACT: case OP_EXACTI: case OP_NOTEXACT: case OP_NOTEXACTI: case OP_UPTO: case OP_UPTOI: case OP_NOTUPTO: case OP_NOTUPTOI: case OP_MINUPTO: case OP_MINUPTOI: case OP_NOTMINUPTO: case OP_NOTMINUPTOI: case OP_POSUPTO: case OP_POSUPTOI: case OP_NOTPOSUPTO: case OP_NOTPOSUPTOI: case OP_STAR: case OP_STARI: case OP_NOTSTAR: case OP_NOTSTARI: case OP_MINSTAR: case OP_MINSTARI: case OP_NOTMINSTAR: case OP_NOTMINSTARI: case OP_POSSTAR: case OP_POSSTARI: case OP_NOTPOSSTAR: case OP_NOTPOSSTARI: case OP_PLUS: case OP_PLUSI: case OP_NOTPLUS: case OP_NOTPLUSI: case OP_MINPLUS: case OP_MINPLUSI: case OP_NOTMINPLUS: case OP_NOTMINPLUSI: case OP_POSPLUS: case OP_POSPLUSI: case OP_NOTPOSPLUS: case OP_NOTPOSPLUSI: case OP_QUERY: case OP_QUERYI: case OP_NOTQUERY: case OP_NOTQUERYI: case OP_MINQUERY: case OP_MINQUERYI: case OP_NOTMINQUERY: case OP_NOTMINQUERYI: case OP_POSQUERY: case OP_POSQUERYI: case OP_NOTPOSQUERY: case OP_NOTPOSQUERYI: if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); break; } #else (void)(utf); /* Keep compiler happy by referencing function argument */ #endif } } } /************************************************* * Scan compiled regex for recursion reference * *************************************************/ /* This little function scans through a compiled pattern until it finds an instance of OP_RECURSE. Arguments: code points to start of expression utf TRUE in UTF-8 / UTF-16 / UTF-32 mode Returns: pointer to the opcode for OP_RECURSE, or NULL if not found */ static const pcre_uchar * find_recurse(const pcre_uchar *code, BOOL utf) { for (;;) { register pcre_uchar c = *code; if (c == OP_END) return NULL; if (c == OP_RECURSE) return code; /* XCLASS is used for classes that cannot be represented just by a bit map. This includes negated single high-valued characters. The length in the table is zero; the actual length is stored in the compiled code. */ if (c == OP_XCLASS) code += GET(code, 1); /* Otherwise, we can get the item's length from the table, except that for repeated character types, we have to test for \p and \P, which have an extra two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we must add in its length. */ else { switch(c) { case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; break; case OP_TYPEPOSUPTO: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2; break; case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: code += code[1]; break; } /* Add in the fixed length from the table */ code += PRIV(OP_lengths)[c]; /* In UTF-8 mode, opcodes that are followed by a character may be followed by a multi-byte character. The length in the table is a minimum, so we have to arrange to skip the extra bytes. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf) switch(c) { case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_EXACT: case OP_EXACTI: case OP_NOTEXACT: case OP_NOTEXACTI: case OP_UPTO: case OP_UPTOI: case OP_NOTUPTO: case OP_NOTUPTOI: case OP_MINUPTO: case OP_MINUPTOI: case OP_NOTMINUPTO: case OP_NOTMINUPTOI: case OP_POSUPTO: case OP_POSUPTOI: case OP_NOTPOSUPTO: case OP_NOTPOSUPTOI: case OP_STAR: case OP_STARI: case OP_NOTSTAR: case OP_NOTSTARI: case OP_MINSTAR: case OP_MINSTARI: case OP_NOTMINSTAR: case OP_NOTMINSTARI: case OP_POSSTAR: case OP_POSSTARI: case OP_NOTPOSSTAR: case OP_NOTPOSSTARI: case OP_PLUS: case OP_PLUSI: case OP_NOTPLUS: case OP_NOTPLUSI: case OP_MINPLUS: case OP_MINPLUSI: case OP_NOTMINPLUS: case OP_NOTMINPLUSI: case OP_POSPLUS: case OP_POSPLUSI: case OP_NOTPOSPLUS: case OP_NOTPOSPLUSI: case OP_QUERY: case OP_QUERYI: case OP_NOTQUERY: case OP_NOTQUERYI: case OP_MINQUERY: case OP_MINQUERYI: case OP_NOTMINQUERY: case OP_NOTMINQUERYI: case OP_POSQUERY: case OP_POSQUERYI: case OP_NOTPOSQUERY: case OP_NOTPOSQUERYI: if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); break; } #else (void)(utf); /* Keep compiler happy by referencing function argument */ #endif } } } /************************************************* * Scan compiled branch for non-emptiness * *************************************************/ /* This function scans through a branch of a compiled pattern to see whether it can match the empty string or not. It is called from could_be_empty() below and from compile_branch() when checking for an unlimited repeat of a group that can match nothing. Note that first_significant_code() skips over backward and negative forward assertions when its final argument is TRUE. If we hit an unclosed bracket, we return "empty" - this means we've struck an inner bracket whose current branch will already have been scanned. Arguments: code points to start of search endcode points to where to stop utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode cd contains pointers to tables etc. recurses chain of recurse_check to catch mutual recursion Returns: TRUE if what is matched could be empty */ static BOOL could_be_empty_branch(const pcre_uchar *code, const pcre_uchar *endcode, BOOL utf, compile_data *cd, recurse_check *recurses) { register pcre_uchar c; recurse_check this_recurse; for (code = first_significant_code(code + PRIV(OP_lengths)[*code], TRUE); code < endcode; code = first_significant_code(code + PRIV(OP_lengths)[c], TRUE)) { const pcre_uchar *ccode; c = *code; /* Skip over forward assertions; the other assertions are skipped by first_significant_code() with a TRUE final argument. */ if (c == OP_ASSERT) { do code += GET(code, 1); while (*code == OP_ALT); c = *code; continue; } /* For a recursion/subroutine call, if its end has been reached, which implies a backward reference subroutine call, we can scan it. If it's a forward reference subroutine call, we can't. To detect forward reference we have to scan up the list that is kept in the workspace. This function is called only when doing the real compile, not during the pre-compile that measures the size of the compiled pattern. */ if (c == OP_RECURSE) { const pcre_uchar *scode = cd->start_code + GET(code, 1); const pcre_uchar *endgroup = scode; BOOL empty_branch; /* Test for forward reference or uncompleted reference. This is disabled when called to scan a completed pattern by setting cd->start_workspace to NULL. */ if (cd->start_workspace != NULL) { const pcre_uchar *tcode; for (tcode = cd->start_workspace; tcode < cd->hwm; tcode += LINK_SIZE) if ((int)GET(tcode, 0) == (int)(code + 1 - cd->start_code)) return TRUE; if (GET(scode, 1) == 0) return TRUE; /* Unclosed */ } /* If the reference is to a completed group, we need to detect whether this is a recursive call, as otherwise there will be an infinite loop. If it is a recursion, just skip over it. Simple recursions are easily detected. For mutual recursions we keep a chain on the stack. */ do endgroup += GET(endgroup, 1); while (*endgroup == OP_ALT); if (code >= scode && code <= endgroup) continue; /* Simple recursion */ else { recurse_check *r = recurses; for (r = recurses; r != NULL; r = r->prev) if (r->group == scode) break; if (r != NULL) continue; /* Mutual recursion */ } /* Completed reference; scan the referenced group, remembering it on the stack chain to detect mutual recursions. */ empty_branch = FALSE; this_recurse.prev = recurses; this_recurse.group = scode; do { if (could_be_empty_branch(scode, endcode, utf, cd, &this_recurse)) { empty_branch = TRUE; break; } scode += GET(scode, 1); } while (*scode == OP_ALT); if (!empty_branch) return FALSE; /* All branches are non-empty */ continue; } /* Groups with zero repeats can of course be empty; skip them. */ if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO || c == OP_BRAPOSZERO) { code += PRIV(OP_lengths)[c]; do code += GET(code, 1); while (*code == OP_ALT); c = *code; continue; } /* A nested group that is already marked as "could be empty" can just be skipped. */ if (c == OP_SBRA || c == OP_SBRAPOS || c == OP_SCBRA || c == OP_SCBRAPOS) { do code += GET(code, 1); while (*code == OP_ALT); c = *code; continue; } /* For other groups, scan the branches. */ if (c == OP_BRA || c == OP_BRAPOS || c == OP_CBRA || c == OP_CBRAPOS || c == OP_ONCE || c == OP_ONCE_NC || c == OP_COND || c == OP_SCOND) { BOOL empty_branch; if (GET(code, 1) == 0) return TRUE; /* Hit unclosed bracket */ /* If a conditional group has only one branch, there is a second, implied, empty branch, so just skip over the conditional, because it could be empty. Otherwise, scan the individual branches of the group. */ if (c == OP_COND && code[GET(code, 1)] != OP_ALT) code += GET(code, 1); else { empty_branch = FALSE; do { if (!empty_branch && could_be_empty_branch(code, endcode, utf, cd, recurses)) empty_branch = TRUE; code += GET(code, 1); } while (*code == OP_ALT); if (!empty_branch) return FALSE; /* All branches are non-empty */ } c = *code; continue; } /* Handle the other opcodes */ switch (c) { /* Check for quantifiers after a class. XCLASS is used for classes that cannot be represented just by a bit map. This includes negated single high-valued characters. The length in PRIV(OP_lengths)[] is zero; the actual length is stored in the compiled code, so we must update "code" here. */ #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: ccode = code += GET(code, 1); goto CHECK_CLASS_REPEAT; #endif case OP_CLASS: case OP_NCLASS: ccode = code + PRIV(OP_lengths)[OP_CLASS]; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 CHECK_CLASS_REPEAT: #endif switch (*ccode) { case OP_CRSTAR: /* These could be empty; continue */ case OP_CRMINSTAR: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSSTAR: case OP_CRPOSQUERY: break; default: /* Non-repeat => class must match */ case OP_CRPLUS: /* These repeats aren't empty */ case OP_CRMINPLUS: case OP_CRPOSPLUS: return FALSE; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: if (GET2(ccode, 1) > 0) return FALSE; /* Minimum > 0 */ break; } break; /* Opcodes that must match a character */ case OP_ANY: case OP_ALLANY: case OP_ANYBYTE: case OP_PROP: case OP_NOTPROP: case OP_ANYNL: case OP_NOT_HSPACE: case OP_HSPACE: case OP_NOT_VSPACE: case OP_VSPACE: case OP_EXTUNI: case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_PLUS: case OP_PLUSI: case OP_MINPLUS: case OP_MINPLUSI: case OP_NOTPLUS: case OP_NOTPLUSI: case OP_NOTMINPLUS: case OP_NOTMINPLUSI: case OP_POSPLUS: case OP_POSPLUSI: case OP_NOTPOSPLUS: case OP_NOTPOSPLUSI: case OP_EXACT: case OP_EXACTI: case OP_NOTEXACT: case OP_NOTEXACTI: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEPOSPLUS: case OP_TYPEEXACT: return FALSE; /* These are going to continue, as they may be empty, but we have to fudge the length for the \p and \P cases. */ case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPOSSTAR: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSQUERY: if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; break; /* Same for these */ case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEPOSUPTO: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2; break; /* End of branch */ case OP_KET: case OP_KETRMAX: case OP_KETRMIN: case OP_KETRPOS: case OP_ALT: return TRUE; /* In UTF-8 mode, STAR, MINSTAR, POSSTAR, QUERY, MINQUERY, POSQUERY, UPTO, MINUPTO, and POSUPTO and their caseless and negative versions may be followed by a multibyte character. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 case OP_STAR: case OP_STARI: case OP_NOTSTAR: case OP_NOTSTARI: case OP_MINSTAR: case OP_MINSTARI: case OP_NOTMINSTAR: case OP_NOTMINSTARI: case OP_POSSTAR: case OP_POSSTARI: case OP_NOTPOSSTAR: case OP_NOTPOSSTARI: case OP_QUERY: case OP_QUERYI: case OP_NOTQUERY: case OP_NOTQUERYI: case OP_MINQUERY: case OP_MINQUERYI: case OP_NOTMINQUERY: case OP_NOTMINQUERYI: case OP_POSQUERY: case OP_POSQUERYI: case OP_NOTPOSQUERY: case OP_NOTPOSQUERYI: if (utf && HAS_EXTRALEN(code[1])) code += GET_EXTRALEN(code[1]); break; case OP_UPTO: case OP_UPTOI: case OP_NOTUPTO: case OP_NOTUPTOI: case OP_MINUPTO: case OP_MINUPTOI: case OP_NOTMINUPTO: case OP_NOTMINUPTOI: case OP_POSUPTO: case OP_POSUPTOI: case OP_NOTPOSUPTO: case OP_NOTPOSUPTOI: if (utf && HAS_EXTRALEN(code[1 + IMM2_SIZE])) code += GET_EXTRALEN(code[1 + IMM2_SIZE]); break; #endif /* MARK, and PRUNE/SKIP/THEN with an argument must skip over the argument string. */ case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: code += code[1]; break; /* None of the remaining opcodes are required to match a character. */ default: break; } } return TRUE; } /************************************************* * Scan compiled regex for non-emptiness * *************************************************/ /* This function is called to check for left recursive calls. We want to check the current branch of the current pattern to see if it could match the empty string. If it could, we must look outwards for branches at other levels, stopping when we pass beyond the bracket which is the subject of the recursion. This function is called only during the real compile, not during the pre-compile. Arguments: code points to start of the recursion endcode points to where to stop (current RECURSE item) bcptr points to the chain of current (unclosed) branch starts utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode cd pointers to tables etc Returns: TRUE if what is matched could be empty */ static BOOL could_be_empty(const pcre_uchar *code, const pcre_uchar *endcode, branch_chain *bcptr, BOOL utf, compile_data *cd) { while (bcptr != NULL && bcptr->current_branch >= code) { if (!could_be_empty_branch(bcptr->current_branch, endcode, utf, cd, NULL)) return FALSE; bcptr = bcptr->outer; } return TRUE; } /************************************************* * Base opcode of repeated opcodes * *************************************************/ /* Returns the base opcode for repeated single character type opcodes. If the opcode is not a repeated character type, it returns with the original value. Arguments: c opcode Returns: base opcode for the type */ static pcre_uchar get_repeat_base(pcre_uchar c) { return (c > OP_TYPEPOSUPTO)? c : (c >= OP_TYPESTAR)? OP_TYPESTAR : (c >= OP_NOTSTARI)? OP_NOTSTARI : (c >= OP_NOTSTAR)? OP_NOTSTAR : (c >= OP_STARI)? OP_STARI : OP_STAR; } #ifdef SUPPORT_UCP /************************************************* * Check a character and a property * *************************************************/ /* This function is called by check_auto_possessive() when a property item is adjacent to a fixed character. Arguments: c the character ptype the property type pdata the data for the type negated TRUE if it's a negated property (\P or \p{^) Returns: TRUE if auto-possessifying is OK */ static BOOL check_char_prop(pcre_uint32 c, unsigned int ptype, unsigned int pdata, BOOL negated) { const pcre_uint32 *p; const ucd_record *prop = GET_UCD(c); switch(ptype) { case PT_LAMP: return (prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || prop->chartype == ucp_Lt) == negated; case PT_GC: return (pdata == PRIV(ucp_gentype)[prop->chartype]) == negated; case PT_PC: return (pdata == prop->chartype) == negated; case PT_SC: return (pdata == prop->script) == negated; /* These are specials */ case PT_ALNUM: return (PRIV(ucp_gentype)[prop->chartype] == ucp_L || PRIV(ucp_gentype)[prop->chartype] == ucp_N) == negated; /* Perl space used to exclude VT, but from Perl 5.18 it is included, which means that Perl space and POSIX space are now identical. PCRE was changed at release 8.34. */ case PT_SPACE: /* Perl space */ case PT_PXSPACE: /* POSIX space */ switch(c) { HSPACE_CASES: VSPACE_CASES: return negated; default: return (PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == negated; } break; /* Control never reaches here */ case PT_WORD: return (PRIV(ucp_gentype)[prop->chartype] == ucp_L || PRIV(ucp_gentype)[prop->chartype] == ucp_N || c == CHAR_UNDERSCORE) == negated; case PT_CLIST: p = PRIV(ucd_caseless_sets) + prop->caseset; for (;;) { if (c < *p) return !negated; if (c == *p++) return negated; } break; /* Control never reaches here */ } return FALSE; } #endif /* SUPPORT_UCP */ /************************************************* * Fill the character property list * *************************************************/ /* Checks whether the code points to an opcode that can take part in auto- possessification, and if so, fills a list with its properties. Arguments: code points to start of expression utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode fcc points to case-flipping table list points to output list list[0] will be filled with the opcode list[1] will be non-zero if this opcode can match an empty character string list[2..7] depends on the opcode Returns: points to the start of the next opcode if *code is accepted NULL if *code is not accepted */ static const pcre_uchar * get_chr_property_list(const pcre_uchar *code, BOOL utf, const pcre_uint8 *fcc, pcre_uint32 *list) { pcre_uchar c = *code; pcre_uchar base; const pcre_uchar *end; pcre_uint32 chr; #ifdef SUPPORT_UCP pcre_uint32 *clist_dest; const pcre_uint32 *clist_src; #else ((void)utf); /* Suppress "unused parameter" compiler warning */ #endif list[0] = c; list[1] = FALSE; code++; if (c >= OP_STAR && c <= OP_TYPEPOSUPTO) { base = get_repeat_base(c); c -= (base - OP_STAR); if (c == OP_UPTO || c == OP_MINUPTO || c == OP_EXACT || c == OP_POSUPTO) code += IMM2_SIZE; list[1] = (c != OP_PLUS && c != OP_MINPLUS && c != OP_EXACT && c != OP_POSPLUS); switch(base) { case OP_STAR: list[0] = OP_CHAR; break; case OP_STARI: list[0] = OP_CHARI; break; case OP_NOTSTAR: list[0] = OP_NOT; break; case OP_NOTSTARI: list[0] = OP_NOTI; break; case OP_TYPESTAR: list[0] = *code; code++; break; } c = list[0]; } switch(c) { case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: case OP_ALLANY: case OP_ANYNL: case OP_NOT_HSPACE: case OP_HSPACE: case OP_NOT_VSPACE: case OP_VSPACE: case OP_EXTUNI: case OP_EODN: case OP_EOD: case OP_DOLL: case OP_DOLLM: return code; case OP_CHAR: case OP_NOT: GETCHARINCTEST(chr, code); list[2] = chr; list[3] = NOTACHAR; return code; case OP_CHARI: case OP_NOTI: list[0] = (c == OP_CHARI) ? OP_CHAR : OP_NOT; GETCHARINCTEST(chr, code); list[2] = chr; #ifdef SUPPORT_UCP if (chr < 128 || (chr < 256 && !utf)) list[3] = fcc[chr]; else list[3] = UCD_OTHERCASE(chr); #elif defined SUPPORT_UTF || !defined COMPILE_PCRE8 list[3] = (chr < 256) ? fcc[chr] : chr; #else list[3] = fcc[chr]; #endif /* The othercase might be the same value. */ if (chr == list[3]) list[3] = NOTACHAR; else list[4] = NOTACHAR; return code; #ifdef SUPPORT_UCP case OP_PROP: case OP_NOTPROP: if (code[0] != PT_CLIST) { list[2] = code[0]; list[3] = code[1]; return code + 2; } /* Convert only if we have enough space. */ clist_src = PRIV(ucd_caseless_sets) + code[1]; clist_dest = list + 2; code += 2; do { if (clist_dest >= list + 8) { /* Early return if there is not enough space. This should never happen, since all clists are shorter than 5 character now. */ list[2] = code[0]; list[3] = code[1]; return code; } *clist_dest++ = *clist_src; } while(*clist_src++ != NOTACHAR); /* All characters are stored. The terminating NOTACHAR is copied form the clist itself. */ list[0] = (c == OP_PROP) ? OP_CHAR : OP_NOT; return code; #endif case OP_NCLASS: case OP_CLASS: #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: if (c == OP_XCLASS) end = code + GET(code, 0) - 1; else #endif end = code + 32 / sizeof(pcre_uchar); switch(*end) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSSTAR: case OP_CRPOSQUERY: list[1] = TRUE; end++; break; case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRPOSPLUS: end++; break; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: list[1] = (GET2(end, 1) == 0); end += 1 + 2 * IMM2_SIZE; break; } list[2] = (pcre_uint32)(end - code); return end; } return NULL; /* Opcode not accepted */ } /************************************************* * Scan further character sets for match * *************************************************/ /* Checks whether the base and the current opcode have a common character, in which case the base cannot be possessified. Arguments: code points to the byte code utf TRUE in UTF-8 / UTF-16 / UTF-32 mode cd static compile data base_list the data list of the base opcode Returns: TRUE if the auto-possessification is possible */ static BOOL compare_opcodes(const pcre_uchar *code, BOOL utf, const compile_data *cd, const pcre_uint32 *base_list, const pcre_uchar *base_end, int *rec_limit) { pcre_uchar c; pcre_uint32 list[8]; const pcre_uint32 *chr_ptr; const pcre_uint32 *ochr_ptr; const pcre_uint32 *list_ptr; const pcre_uchar *next_code; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 const pcre_uchar *xclass_flags; #endif const pcre_uint8 *class_bitset; const pcre_uint8 *set1, *set2, *set_end; pcre_uint32 chr; BOOL accepted, invert_bits; BOOL entered_a_group = FALSE; if (*rec_limit == 0) return FALSE; --(*rec_limit); /* Note: the base_list[1] contains whether the current opcode has greedy (represented by a non-zero value) quantifier. This is a different from other character type lists, which stores here that the character iterator matches to an empty string (also represented by a non-zero value). */ for(;;) { /* All operations move the code pointer forward. Therefore infinite recursions are not possible. */ c = *code; /* Skip over callouts */ if (c == OP_CALLOUT) { code += PRIV(OP_lengths)[c]; continue; } if (c == OP_ALT) { do code += GET(code, 1); while (*code == OP_ALT); c = *code; } switch(c) { case OP_END: case OP_KETRPOS: /* TRUE only in greedy case. The non-greedy case could be replaced by an OP_EXACT, but it is probably not worth it. (And note that OP_EXACT uses more memory, which we cannot get at this stage.) */ return base_list[1] != 0; case OP_KET: /* If the bracket is capturing, and referenced by an OP_RECURSE, or it is an atomic sub-pattern (assert, once, etc.) the non-greedy case cannot be converted to a possessive form. */ if (base_list[1] == 0) return FALSE; switch(*(code - GET(code, 1))) { case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_ONCE_NC: /* Atomic sub-patterns and assertions can always auto-possessify their last iterator. However, if the group was entered as a result of checking a previous iterator, this is not possible. */ return !entered_a_group; } code += PRIV(OP_lengths)[c]; continue; case OP_ONCE: case OP_ONCE_NC: case OP_BRA: case OP_CBRA: next_code = code + GET(code, 1); code += PRIV(OP_lengths)[c]; while (*next_code == OP_ALT) { if (!compare_opcodes(code, utf, cd, base_list, base_end, rec_limit)) return FALSE; code = next_code + 1 + LINK_SIZE; next_code += GET(next_code, 1); } entered_a_group = TRUE; continue; case OP_BRAZERO: case OP_BRAMINZERO: next_code = code + 1; if (*next_code != OP_BRA && *next_code != OP_CBRA && *next_code != OP_ONCE && *next_code != OP_ONCE_NC) return FALSE; do next_code += GET(next_code, 1); while (*next_code == OP_ALT); /* The bracket content will be checked by the OP_BRA/OP_CBRA case above. */ next_code += 1 + LINK_SIZE; if (!compare_opcodes(next_code, utf, cd, base_list, base_end, rec_limit)) return FALSE; code += PRIV(OP_lengths)[c]; continue; default: break; } /* Check for a supported opcode, and load its properties. */ code = get_chr_property_list(code, utf, cd->fcc, list); if (code == NULL) return FALSE; /* Unsupported */ /* If either opcode is a small character list, set pointers for comparing characters from that list with another list, or with a property. */ if (base_list[0] == OP_CHAR) { chr_ptr = base_list + 2; list_ptr = list; } else if (list[0] == OP_CHAR) { chr_ptr = list + 2; list_ptr = base_list; } /* Character bitsets can also be compared to certain opcodes. */ else if (base_list[0] == OP_CLASS || list[0] == OP_CLASS #ifdef COMPILE_PCRE8 /* In 8 bit, non-UTF mode, OP_CLASS and OP_NCLASS are the same. */ || (!utf && (base_list[0] == OP_NCLASS || list[0] == OP_NCLASS)) #endif ) { #ifdef COMPILE_PCRE8 if (base_list[0] == OP_CLASS || (!utf && base_list[0] == OP_NCLASS)) #else if (base_list[0] == OP_CLASS) #endif { set1 = (pcre_uint8 *)(base_end - base_list[2]); list_ptr = list; } else { set1 = (pcre_uint8 *)(code - list[2]); list_ptr = base_list; } invert_bits = FALSE; switch(list_ptr[0]) { case OP_CLASS: case OP_NCLASS: set2 = (pcre_uint8 *) ((list_ptr == list ? code : base_end) - list_ptr[2]); break; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: xclass_flags = (list_ptr == list ? code : base_end) - list_ptr[2] + LINK_SIZE; if ((*xclass_flags & XCL_HASPROP) != 0) return FALSE; if ((*xclass_flags & XCL_MAP) == 0) { /* No bits are set for characters < 256. */ if (list[1] == 0) return (*xclass_flags & XCL_NOT) == 0; /* Might be an empty repeat. */ continue; } set2 = (pcre_uint8 *)(xclass_flags + 1); break; #endif case OP_NOT_DIGIT: invert_bits = TRUE; /* Fall through */ case OP_DIGIT: set2 = (pcre_uint8 *)(cd->cbits + cbit_digit); break; case OP_NOT_WHITESPACE: invert_bits = TRUE; /* Fall through */ case OP_WHITESPACE: set2 = (pcre_uint8 *)(cd->cbits + cbit_space); break; case OP_NOT_WORDCHAR: invert_bits = TRUE; /* Fall through */ case OP_WORDCHAR: set2 = (pcre_uint8 *)(cd->cbits + cbit_word); break; default: return FALSE; } /* Because the sets are unaligned, we need to perform byte comparison here. */ set_end = set1 + 32; if (invert_bits) { do { if ((*set1++ & ~(*set2++)) != 0) return FALSE; } while (set1 < set_end); } else { do { if ((*set1++ & *set2++) != 0) return FALSE; } while (set1 < set_end); } if (list[1] == 0) return TRUE; /* Might be an empty repeat. */ continue; } /* Some property combinations also acceptable. Unicode property opcodes are processed specially; the rest can be handled with a lookup table. */ else { pcre_uint32 leftop, rightop; leftop = base_list[0]; rightop = list[0]; #ifdef SUPPORT_UCP accepted = FALSE; /* Always set in non-unicode case. */ if (leftop == OP_PROP || leftop == OP_NOTPROP) { if (rightop == OP_EOD) accepted = TRUE; else if (rightop == OP_PROP || rightop == OP_NOTPROP) { int n; const pcre_uint8 *p; BOOL same = leftop == rightop; BOOL lisprop = leftop == OP_PROP; BOOL risprop = rightop == OP_PROP; BOOL bothprop = lisprop && risprop; /* There's a table that specifies how each combination is to be processed: 0 Always return FALSE (never auto-possessify) 1 Character groups are distinct (possessify if both are OP_PROP) 2 Check character categories in the same group (general or particular) 3 Return TRUE if the two opcodes are not the same ... see comments below */ n = propposstab[base_list[2]][list[2]]; switch(n) { case 0: break; case 1: accepted = bothprop; break; case 2: accepted = (base_list[3] == list[3]) != same; break; case 3: accepted = !same; break; case 4: /* Left general category, right particular category */ accepted = risprop && catposstab[base_list[3]][list[3]] == same; break; case 5: /* Right general category, left particular category */ accepted = lisprop && catposstab[list[3]][base_list[3]] == same; break; /* This code is logically tricky. Think hard before fiddling with it. The posspropstab table has four entries per row. Each row relates to one of PCRE's special properties such as ALNUM or SPACE or WORD. Only WORD actually needs all four entries, but using repeats for the others means they can all use the same code below. The first two entries in each row are Unicode general categories, and apply always, because all the characters they include are part of the PCRE character set. The third and fourth entries are a general and a particular category, respectively, that include one or more relevant characters. One or the other is used, depending on whether the check is for a general or a particular category. However, in both cases the category contains more characters than the specials that are defined for the property being tested against. Therefore, it cannot be used in a NOTPROP case. Example: the row for WORD contains ucp_L, ucp_N, ucp_P, ucp_Po. Underscore is covered by ucp_P or ucp_Po. */ case 6: /* Left alphanum vs right general category */ case 7: /* Left space vs right general category */ case 8: /* Left word vs right general category */ p = posspropstab[n-6]; accepted = risprop && lisprop == (list[3] != p[0] && list[3] != p[1] && (list[3] != p[2] || !lisprop)); break; case 9: /* Right alphanum vs left general category */ case 10: /* Right space vs left general category */ case 11: /* Right word vs left general category */ p = posspropstab[n-9]; accepted = lisprop && risprop == (base_list[3] != p[0] && base_list[3] != p[1] && (base_list[3] != p[2] || !risprop)); break; case 12: /* Left alphanum vs right particular category */ case 13: /* Left space vs right particular category */ case 14: /* Left word vs right particular category */ p = posspropstab[n-12]; accepted = risprop && lisprop == (catposstab[p[0]][list[3]] && catposstab[p[1]][list[3]] && (list[3] != p[3] || !lisprop)); break; case 15: /* Right alphanum vs left particular category */ case 16: /* Right space vs left particular category */ case 17: /* Right word vs left particular category */ p = posspropstab[n-15]; accepted = lisprop && risprop == (catposstab[p[0]][base_list[3]] && catposstab[p[1]][base_list[3]] && (base_list[3] != p[3] || !risprop)); break; } } } else #endif /* SUPPORT_UCP */ accepted = leftop >= FIRST_AUTOTAB_OP && leftop <= LAST_AUTOTAB_LEFT_OP && rightop >= FIRST_AUTOTAB_OP && rightop <= LAST_AUTOTAB_RIGHT_OP && autoposstab[leftop - FIRST_AUTOTAB_OP][rightop - FIRST_AUTOTAB_OP]; if (!accepted) return FALSE; if (list[1] == 0) return TRUE; /* Might be an empty repeat. */ continue; } /* Control reaches here only if one of the items is a small character list. All characters are checked against the other side. */ do { chr = *chr_ptr; switch(list_ptr[0]) { case OP_CHAR: ochr_ptr = list_ptr + 2; do { if (chr == *ochr_ptr) return FALSE; ochr_ptr++; } while(*ochr_ptr != NOTACHAR); break; case OP_NOT: ochr_ptr = list_ptr + 2; do { if (chr == *ochr_ptr) break; ochr_ptr++; } while(*ochr_ptr != NOTACHAR); if (*ochr_ptr == NOTACHAR) return FALSE; /* Not found */ break; /* Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* set. When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */ case OP_DIGIT: if (chr < 256 && (cd->ctypes[chr] & ctype_digit) != 0) return FALSE; break; case OP_NOT_DIGIT: if (chr > 255 || (cd->ctypes[chr] & ctype_digit) == 0) return FALSE; break; case OP_WHITESPACE: if (chr < 256 && (cd->ctypes[chr] & ctype_space) != 0) return FALSE; break; case OP_NOT_WHITESPACE: if (chr > 255 || (cd->ctypes[chr] & ctype_space) == 0) return FALSE; break; case OP_WORDCHAR: if (chr < 255 && (cd->ctypes[chr] & ctype_word) != 0) return FALSE; break; case OP_NOT_WORDCHAR: if (chr > 255 || (cd->ctypes[chr] & ctype_word) == 0) return FALSE; break; case OP_HSPACE: switch(chr) { HSPACE_CASES: return FALSE; default: break; } break; case OP_NOT_HSPACE: switch(chr) { HSPACE_CASES: break; default: return FALSE; } break; case OP_ANYNL: case OP_VSPACE: switch(chr) { VSPACE_CASES: return FALSE; default: break; } break; case OP_NOT_VSPACE: switch(chr) { VSPACE_CASES: break; default: return FALSE; } break; case OP_DOLL: case OP_EODN: switch (chr) { case CHAR_CR: case CHAR_LF: case CHAR_VT: case CHAR_FF: case CHAR_NEL: #ifndef EBCDIC case 0x2028: case 0x2029: #endif /* Not EBCDIC */ return FALSE; } break; case OP_EOD: /* Can always possessify before \z */ break; #ifdef SUPPORT_UCP case OP_PROP: case OP_NOTPROP: if (!check_char_prop(chr, list_ptr[2], list_ptr[3], list_ptr[0] == OP_NOTPROP)) return FALSE; break; #endif case OP_NCLASS: if (chr > 255) return FALSE; /* Fall through */ case OP_CLASS: if (chr > 255) break; class_bitset = (pcre_uint8 *) ((list_ptr == list ? code : base_end) - list_ptr[2]); if ((class_bitset[chr >> 3] & (1U << (chr & 7))) != 0) return FALSE; break; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: if (PRIV(xclass)(chr, (list_ptr == list ? code : base_end) - list_ptr[2] + LINK_SIZE, utf)) return FALSE; break; #endif default: return FALSE; } chr_ptr++; } while(*chr_ptr != NOTACHAR); /* At least one character must be matched from this opcode. */ if (list[1] == 0) return TRUE; } /* Control never reaches here. There used to be a fail-save return FALSE; here, but some compilers complain about an unreachable statement. */ } /************************************************* * Scan compiled regex for auto-possession * *************************************************/ /* Replaces single character iterations with their possessive alternatives if appropriate. This function modifies the compiled opcode! Arguments: code points to start of the byte code utf TRUE in UTF-8 / UTF-16 / UTF-32 mode cd static compile data Returns: nothing */ static void auto_possessify(pcre_uchar *code, BOOL utf, const compile_data *cd) { register pcre_uchar c; const pcre_uchar *end; pcre_uchar *repeat_opcode; pcre_uint32 list[8]; int rec_limit; for (;;) { c = *code; /* When a pattern with bad UTF-8 encoding is compiled with NO_UTF_CHECK, it may compile without complaining, but may get into a loop here if the code pointer points to a bad value. This is, of course a documentated possibility, when NO_UTF_CHECK is set, so it isn't a bug, but we can detect this case and just give up on this optimization. */ if (c >= OP_TABLE_LENGTH) return; if (c >= OP_STAR && c <= OP_TYPEPOSUPTO) { c -= get_repeat_base(c) - OP_STAR; end = (c <= OP_MINUPTO) ? get_chr_property_list(code, utf, cd->fcc, list) : NULL; list[1] = c == OP_STAR || c == OP_PLUS || c == OP_QUERY || c == OP_UPTO; rec_limit = 1000; if (end != NULL && compare_opcodes(end, utf, cd, list, end, &rec_limit)) { switch(c) { case OP_STAR: *code += OP_POSSTAR - OP_STAR; break; case OP_MINSTAR: *code += OP_POSSTAR - OP_MINSTAR; break; case OP_PLUS: *code += OP_POSPLUS - OP_PLUS; break; case OP_MINPLUS: *code += OP_POSPLUS - OP_MINPLUS; break; case OP_QUERY: *code += OP_POSQUERY - OP_QUERY; break; case OP_MINQUERY: *code += OP_POSQUERY - OP_MINQUERY; break; case OP_UPTO: *code += OP_POSUPTO - OP_UPTO; break; case OP_MINUPTO: *code += OP_POSUPTO - OP_MINUPTO; break; } } c = *code; } else if (c == OP_CLASS || c == OP_NCLASS || c == OP_XCLASS) { #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 if (c == OP_XCLASS) repeat_opcode = code + GET(code, 1); else #endif repeat_opcode = code + 1 + (32 / sizeof(pcre_uchar)); c = *repeat_opcode; if (c >= OP_CRSTAR && c <= OP_CRMINRANGE) { /* end must not be NULL. */ end = get_chr_property_list(code, utf, cd->fcc, list); list[1] = (c & 1) == 0; rec_limit = 1000; if (compare_opcodes(end, utf, cd, list, end, &rec_limit)) { switch (c) { case OP_CRSTAR: case OP_CRMINSTAR: *repeat_opcode = OP_CRPOSSTAR; break; case OP_CRPLUS: case OP_CRMINPLUS: *repeat_opcode = OP_CRPOSPLUS; break; case OP_CRQUERY: case OP_CRMINQUERY: *repeat_opcode = OP_CRPOSQUERY; break; case OP_CRRANGE: case OP_CRMINRANGE: *repeat_opcode = OP_CRPOSRANGE; break; } } } c = *code; } switch(c) { case OP_END: return; case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; break; case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSUPTO: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) code += 2; break; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: code += GET(code, 1); break; #endif case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: code += code[1]; break; } /* Add in the fixed length from the table */ code += PRIV(OP_lengths)[c]; /* In UTF-8 mode, opcodes that are followed by a character may be followed by a multi-byte character. The length in the table is a minimum, so we have to arrange to skip the extra bytes. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf) switch(c) { case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_UPTOI: case OP_MINUPTOI: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); break; } #else (void)(utf); /* Keep compiler happy by referencing function argument */ #endif } } /************************************************* * Check for POSIX class syntax * *************************************************/ /* This function is called when the sequence "[:" or "[." or "[=" is encountered in a character class. It checks whether this is followed by a sequence of characters terminated by a matching ":]" or ".]" or "=]". If we reach an unescaped ']' without the special preceding character, return FALSE. Originally, this function only recognized a sequence of letters between the terminators, but it seems that Perl recognizes any sequence of characters, though of course unknown POSIX names are subsequently rejected. Perl gives an "Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE didn't consider this to be a POSIX class. Likewise for [:1234:]. The problem in trying to be exactly like Perl is in the handling of escapes. We have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code below handles the special cases \\ and \], but does not try to do any other escape processing. This makes it different from Perl for cases such as [:l\ower:] where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize "l\ower". This is a lesser evil than not diagnosing bad classes when Perl does, I think. A user pointed out that PCRE was rejecting [:a[:digit:]] whereas Perl was not. It seems that the appearance of a nested POSIX class supersedes an apparent external class. For example, [:a[:digit:]b:] matches "a", "b", ":", or a digit. In Perl, unescaped square brackets may also appear as part of class names. For example, [:a[:abc]b:] gives unknown POSIX class "[:abc]b:]". However, for [:a[:abc]b][b:] it gives unknown POSIX class "[:abc]b][b:]", which does not seem right at all. PCRE does not allow closing square brackets in POSIX class names. Arguments: ptr pointer to the initial [ endptr where to return the end pointer Returns: TRUE or FALSE */ static BOOL check_posix_syntax(const pcre_uchar *ptr, const pcre_uchar **endptr) { pcre_uchar terminator; /* Don't combine these lines; the Solaris cc */ terminator = *(++ptr); /* compiler warns about "non-constant" initializer. */ for (++ptr; *ptr != CHAR_NULL; ptr++) { if (*ptr == CHAR_BACKSLASH && (ptr[1] == CHAR_RIGHT_SQUARE_BRACKET || ptr[1] == CHAR_BACKSLASH)) ptr++; else if ((*ptr == CHAR_LEFT_SQUARE_BRACKET && ptr[1] == terminator) || *ptr == CHAR_RIGHT_SQUARE_BRACKET) return FALSE; else if (*ptr == terminator && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) { *endptr = ptr; return TRUE; } } return FALSE; } /************************************************* * Check POSIX class name * *************************************************/ /* This function is called to check the name given in a POSIX-style class entry such as [:alnum:]. Arguments: ptr points to the first letter len the length of the name Returns: a value representing the name, or -1 if unknown */ static int check_posix_name(const pcre_uchar *ptr, int len) { const char *pn = posix_names; register int yield = 0; while (posix_name_lengths[yield] != 0) { if (len == posix_name_lengths[yield] && STRNCMP_UC_C8(ptr, pn, (unsigned int)len) == 0) return yield; pn += posix_name_lengths[yield] + 1; yield++; } return -1; } /************************************************* * Adjust OP_RECURSE items in repeated group * *************************************************/ /* OP_RECURSE items contain an offset from the start of the regex to the group that is referenced. This means that groups can be replicated for fixed repetition simply by copying (because the recursion is allowed to refer to earlier groups that are outside the current group). However, when a group is optional (i.e. the minimum quantifier is zero), OP_BRAZERO or OP_SKIPZERO is inserted before it, after it has been compiled. This means that any OP_RECURSE items within it that refer to the group itself or any contained groups have to have their offsets adjusted. That one of the jobs of this function. Before it is called, the partially compiled regex must be temporarily terminated with OP_END. This function has been extended to cope with forward references for recursions and subroutine calls. It must check the list of such references for the group we are dealing with. If it finds that one of the recursions in the current group is on this list, it does not adjust the value in the reference (which is a group number). After the group has been scanned, all the offsets in the forward reference list for the group are adjusted. Arguments: group points to the start of the group adjust the amount by which the group is to be moved utf TRUE in UTF-8 / UTF-16 / UTF-32 mode cd contains pointers to tables etc. save_hwm_offset the hwm forward reference offset at the start of the group Returns: nothing */ static void adjust_recurse(pcre_uchar *group, int adjust, BOOL utf, compile_data *cd, size_t save_hwm_offset) { int offset; pcre_uchar *hc; pcre_uchar *ptr = group; while ((ptr = (pcre_uchar *)find_recurse(ptr, utf)) != NULL) { for (hc = (pcre_uchar *)cd->start_workspace + save_hwm_offset; hc < cd->hwm; hc += LINK_SIZE) { offset = (int)GET(hc, 0); if (cd->start_code + offset == ptr + 1) break; } /* If we have not found this recursion on the forward reference list, adjust the recursion's offset if it's after the start of this group. */ if (hc >= cd->hwm) { offset = (int)GET(ptr, 1); if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust); } ptr += 1 + LINK_SIZE; } /* Now adjust all forward reference offsets for the group. */ for (hc = (pcre_uchar *)cd->start_workspace + save_hwm_offset; hc < cd->hwm; hc += LINK_SIZE) { offset = (int)GET(hc, 0); PUT(hc, 0, offset + adjust); } } /************************************************* * Insert an automatic callout point * *************************************************/ /* This function is called when the PCRE_AUTO_CALLOUT option is set, to insert callout points before each pattern item. Arguments: code current code pointer ptr current pattern pointer cd pointers to tables etc Returns: new code pointer */ static pcre_uchar * auto_callout(pcre_uchar *code, const pcre_uchar *ptr, compile_data *cd) { *code++ = OP_CALLOUT; *code++ = 255; PUT(code, 0, (int)(ptr - cd->start_pattern)); /* Pattern offset */ PUT(code, LINK_SIZE, 0); /* Default length */ return code + 2 * LINK_SIZE; } /************************************************* * Complete a callout item * *************************************************/ /* A callout item contains the length of the next item in the pattern, which we can't fill in till after we have reached the relevant point. This is used for both automatic and manual callouts. Arguments: previous_callout points to previous callout item ptr current pattern pointer cd pointers to tables etc Returns: nothing */ static void complete_callout(pcre_uchar *previous_callout, const pcre_uchar *ptr, compile_data *cd) { int length = (int)(ptr - cd->start_pattern - GET(previous_callout, 2)); PUT(previous_callout, 2 + LINK_SIZE, length); } #ifdef SUPPORT_UCP /************************************************* * Get othercase range * *************************************************/ /* This function is passed the start and end of a class range, in UTF-8 mode with UCP support. It searches up the characters, looking for ranges of characters in the "other" case. Each call returns the next one, updating the start address. A character with multiple other cases is returned on its own with a special return value. Arguments: cptr points to starting character value; updated d end value ocptr where to put start of othercase range odptr where to put end of othercase range Yield: -1 when no more 0 when a range is returned >0 the CASESET offset for char with multiple other cases in this case, ocptr contains the original */ static int get_othercase_range(pcre_uint32 *cptr, pcre_uint32 d, pcre_uint32 *ocptr, pcre_uint32 *odptr) { pcre_uint32 c, othercase, next; unsigned int co; /* Find the first character that has an other case. If it has multiple other cases, return its case offset value. */ for (c = *cptr; c <= d; c++) { if ((co = UCD_CASESET(c)) != 0) { *ocptr = c++; /* Character that has the set */ *cptr = c; /* Rest of input range */ return (int)co; } if ((othercase = UCD_OTHERCASE(c)) != c) break; } if (c > d) return -1; /* Reached end of range */ /* Found a character that has a single other case. Search for the end of the range, which is either the end of the input range, or a character that has zero or more than one other cases. */ *ocptr = othercase; next = othercase + 1; for (++c; c <= d; c++) { if ((co = UCD_CASESET(c)) != 0 || UCD_OTHERCASE(c) != next) break; next++; } *odptr = next - 1; /* End of othercase range */ *cptr = c; /* Rest of input range */ return 0; } #endif /* SUPPORT_UCP */ /************************************************* * Add a character or range to a class * *************************************************/ /* This function packages up the logic of adding a character or range of characters to a class. The character values in the arguments will be within the valid values for the current mode (8-bit, 16-bit, UTF, etc). This function is mutually recursive with the function immediately below. Arguments: classbits the bit map for characters < 256 uchardptr points to the pointer for extra data options the options word cd contains pointers to tables etc. start start of range character end end of range character Returns: the number of < 256 characters added the pointer to extra data is updated */ static int add_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, compile_data *cd, pcre_uint32 start, pcre_uint32 end) { pcre_uint32 c; pcre_uint32 classbits_end = (end <= 0xff ? end : 0xff); int n8 = 0; ((void)uchardptr); ((void)propposstab); ((void)catposstab); ((void)posspropstab); /* If caseless matching is required, scan the range and process alternate cases. In Unicode, there are 8-bit characters that have alternate cases that are greater than 255 and vice-versa. Sometimes we can just extend the original range. */ if ((options & PCRE_CASELESS) != 0) { #ifdef SUPPORT_UCP if ((options & PCRE_UTF8) != 0) { int rc; pcre_uint32 oc, od; options &= ~PCRE_CASELESS; /* Remove for recursive calls */ c = start; while ((rc = get_othercase_range(&c, end, &oc, &od)) >= 0) { /* Handle a single character that has more than one other case. */ if (rc > 0) n8 += add_list_to_class(classbits, uchardptr, options, cd, PRIV(ucd_caseless_sets) + rc, oc); /* Do nothing if the other case range is within the original range. */ else if (oc >= start && od <= end) continue; /* Extend the original range if there is overlap, noting that if oc < c, we can't have od > end because a subrange is always shorter than the basic range. Otherwise, use a recursive call to add the additional range. */ else if (oc < start && od >= start - 1) start = oc; /* Extend downwards */ else if (od > end && oc <= end + 1) { end = od; /* Extend upwards */ if (end > classbits_end) classbits_end = (end <= 0xff ? end : 0xff); } else n8 += add_to_class(classbits, uchardptr, options, cd, oc, od); } } else #endif /* SUPPORT_UCP */ /* Not UTF-mode, or no UCP */ for (c = start; c <= classbits_end; c++) { SETBIT(classbits, cd->fcc[c]); n8++; } } /* Now handle the original range. Adjust the final value according to the bit length - this means that the same lists of (e.g.) horizontal spaces can be used in all cases. */ #if defined COMPILE_PCRE8 #ifdef SUPPORT_UTF if ((options & PCRE_UTF8) == 0) #endif if (end > 0xff) end = 0xff; #elif defined COMPILE_PCRE16 #ifdef SUPPORT_UTF if ((options & PCRE_UTF16) == 0) #endif if (end > 0xffff) end = 0xffff; #endif /* COMPILE_PCRE[8|16] */ /* Use the bitmap for characters < 256. Otherwise use extra data.*/ for (c = start; c <= classbits_end; c++) { /* Regardless of start, c will always be <= 255. */ SETBIT(classbits, c); n8++; } #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 if (start <= 0xff) start = 0xff + 1; if (end >= start) { pcre_uchar *uchardata = *uchardptr; #ifdef SUPPORT_UTF if ((options & PCRE_UTF8) != 0) /* All UTFs use the same flag bit */ { if (start < end) { *uchardata++ = XCL_RANGE; uchardata += PRIV(ord2utf)(start, uchardata); uchardata += PRIV(ord2utf)(end, uchardata); } else if (start == end) { *uchardata++ = XCL_SINGLE; uchardata += PRIV(ord2utf)(start, uchardata); } } else #endif /* SUPPORT_UTF */ /* Without UTF support, character values are constrained by the bit length, and can only be > 256 for 16-bit and 32-bit libraries. */ #ifdef COMPILE_PCRE8 {} #else if (start < end) { *uchardata++ = XCL_RANGE; *uchardata++ = start; *uchardata++ = end; } else if (start == end) { *uchardata++ = XCL_SINGLE; *uchardata++ = start; } #endif *uchardptr = uchardata; /* Updata extra data pointer */ } #endif /* SUPPORT_UTF || !COMPILE_PCRE8 */ return n8; /* Number of 8-bit characters */ } /************************************************* * Add a list of characters to a class * *************************************************/ /* This function is used for adding a list of case-equivalent characters to a class, and also for adding a list of horizontal or vertical whitespace. If the list is in order (which it should be), ranges of characters are detected and handled appropriately. This function is mutually recursive with the function above. Arguments: classbits the bit map for characters < 256 uchardptr points to the pointer for extra data options the options word cd contains pointers to tables etc. p points to row of 32-bit values, terminated by NOTACHAR except character to omit; this is used when adding lists of case-equivalent characters to avoid including the one we already know about Returns: the number of < 256 characters added the pointer to extra data is updated */ static int add_list_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, compile_data *cd, const pcre_uint32 *p, unsigned int except) { int n8 = 0; while (p[0] < NOTACHAR) { int n = 0; if (p[0] != except) { while(p[n+1] == p[0] + n + 1) n++; n8 += add_to_class(classbits, uchardptr, options, cd, p[0], p[n]); } p += n + 1; } return n8; } /************************************************* * Add characters not in a list to a class * *************************************************/ /* This function is used for adding the complement of a list of horizontal or vertical whitespace to a class. The list must be in order. Arguments: classbits the bit map for characters < 256 uchardptr points to the pointer for extra data options the options word cd contains pointers to tables etc. p points to row of 32-bit values, terminated by NOTACHAR Returns: the number of < 256 characters added the pointer to extra data is updated */ static int add_not_list_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, compile_data *cd, const pcre_uint32 *p) { BOOL utf = (options & PCRE_UTF8) != 0; int n8 = 0; if (p[0] > 0) n8 += add_to_class(classbits, uchardptr, options, cd, 0, p[0] - 1); while (p[0] < NOTACHAR) { while (p[1] == p[0] + 1) p++; n8 += add_to_class(classbits, uchardptr, options, cd, p[0] + 1, (p[1] == NOTACHAR) ? (utf ? 0x10ffffu : 0xffffffffu) : p[1] - 1); p++; } return n8; } /************************************************* * Compile one branch * *************************************************/ /* Scan the pattern, compiling it into the a vector. If the options are changed during the branch, the pointer is used to change the external options bits. This function is used during the pre-compile phase when we are trying to find out the amount of memory needed, as well as during the real compile phase. The value of lengthptr distinguishes the two phases. Arguments: optionsptr pointer to the option bits codeptr points to the pointer to the current code point ptrptr points to the current pattern pointer errorcodeptr points to error code variable firstcharptr place to put the first required character firstcharflagsptr place to put the first character flags, or a negative number reqcharptr place to put the last required character reqcharflagsptr place to put the last required character flags, or a negative number bcptr points to current branch chain cond_depth conditional nesting depth cd contains pointers to tables etc. lengthptr NULL during the real compile phase points to length accumulator during pre-compile phase Returns: TRUE on success FALSE, with *errorcodeptr set non-zero on error */ static BOOL compile_branch(int *optionsptr, pcre_uchar **codeptr, const pcre_uchar **ptrptr, int *errorcodeptr, pcre_uint32 *firstcharptr, pcre_int32 *firstcharflagsptr, pcre_uint32 *reqcharptr, pcre_int32 *reqcharflagsptr, branch_chain *bcptr, int cond_depth, compile_data *cd, int *lengthptr) { int repeat_type, op_type; int repeat_min = 0, repeat_max = 0; /* To please picky compilers */ int bravalue = 0; int greedy_default, greedy_non_default; pcre_uint32 firstchar, reqchar; pcre_int32 firstcharflags, reqcharflags; pcre_uint32 zeroreqchar, zerofirstchar; pcre_int32 zeroreqcharflags, zerofirstcharflags; pcre_int32 req_caseopt, reqvary, tempreqvary; int options = *optionsptr; /* May change dynamically */ int after_manual_callout = 0; int length_prevgroup = 0; register pcre_uint32 c; int escape; register pcre_uchar *code = *codeptr; pcre_uchar *last_code = code; pcre_uchar *orig_code = code; pcre_uchar *tempcode; BOOL inescq = FALSE; BOOL groupsetfirstchar = FALSE; const pcre_uchar *ptr = *ptrptr; const pcre_uchar *tempptr; const pcre_uchar *nestptr = NULL; pcre_uchar *previous = NULL; pcre_uchar *previous_callout = NULL; size_t item_hwm_offset = 0; pcre_uint8 classbits[32]; /* We can fish out the UTF-8 setting once and for all into a BOOL, but we must not do this for other options (e.g. PCRE_EXTENDED) because they may change dynamically as we process the pattern. */ #ifdef SUPPORT_UTF /* PCRE_UTF[16|32] have the same value as PCRE_UTF8. */ BOOL utf = (options & PCRE_UTF8) != 0; #ifndef COMPILE_PCRE32 pcre_uchar utf_chars[6]; #endif #else BOOL utf = FALSE; #endif /* Helper variables for OP_XCLASS opcode (for characters > 255). We define class_uchardata always so that it can be passed to add_to_class() always, though it will not be used in non-UTF 8-bit cases. This avoids having to supply alternative calls for the different cases. */ pcre_uchar *class_uchardata; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 BOOL xclass; pcre_uchar *class_uchardata_base; #endif #ifdef PCRE_DEBUG if (lengthptr != NULL) DPRINTF((">> start branch\n")); #endif /* Set up the default and non-default settings for greediness */ greedy_default = ((options & PCRE_UNGREEDY) != 0); greedy_non_default = greedy_default ^ 1; /* Initialize no first byte, no required byte. REQ_UNSET means "no char matching encountered yet". It gets changed to REQ_NONE if we hit something that matches a non-fixed char first char; reqchar just remains unset if we never find one. When we hit a repeat whose minimum is zero, we may have to adjust these values to take the zero repeat into account. This is implemented by setting them to zerofirstbyte and zeroreqchar when such a repeat is encountered. The individual item types that can be repeated set these backoff variables appropriately. */ firstchar = reqchar = zerofirstchar = zeroreqchar = 0; firstcharflags = reqcharflags = zerofirstcharflags = zeroreqcharflags = REQ_UNSET; /* The variable req_caseopt contains either the REQ_CASELESS value or zero, according to the current setting of the caseless flag. The REQ_CASELESS leaves the lower 28 bit empty. It is added into the firstchar or reqchar variables to record the case status of the value. This is used only for ASCII characters. */ req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS:0; /* Switch on next character until the end of the branch */ for (;; ptr++) { BOOL negate_class; BOOL should_flip_negation; BOOL possessive_quantifier; BOOL is_quantifier; BOOL is_recurse; BOOL reset_bracount; int class_has_8bitchar; int class_one_char; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 BOOL xclass_has_prop; #endif int newoptions; int recno; int refsign; int skipbytes; pcre_uint32 subreqchar, subfirstchar; pcre_int32 subreqcharflags, subfirstcharflags; int terminator; unsigned int mclength; unsigned int tempbracount; pcre_uint32 ec; pcre_uchar mcbuffer[8]; /* Come here to restart the loop without advancing the pointer. */ REDO_LOOP: /* Get next character in the pattern */ c = *ptr; /* If we are at the end of a nested substitution, revert to the outer level string. Nesting only happens one level deep. */ if (c == CHAR_NULL && nestptr != NULL) { ptr = nestptr; nestptr = NULL; c = *ptr; } /* If we are in the pre-compile phase, accumulate the length used for the previous cycle of this loop. */ if (lengthptr != NULL) { #ifdef PCRE_DEBUG if (code > cd->hwm) cd->hwm = code; /* High water info */ #endif if (code > cd->start_workspace + cd->workspace_size - WORK_SIZE_SAFETY_MARGIN) /* Check for overrun */ { *errorcodeptr = (code >= cd->start_workspace + cd->workspace_size)? ERR52 : ERR87; goto FAILED; } /* There is at least one situation where code goes backwards: this is the case of a zero quantifier after a class (e.g. [ab]{0}). At compile time, the class is simply eliminated. However, it is created first, so we have to allow memory for it. Therefore, don't ever reduce the length at this point. */ if (code < last_code) code = last_code; /* Paranoid check for integer overflow */ if (OFLOW_MAX - *lengthptr < code - last_code) { *errorcodeptr = ERR20; goto FAILED; } *lengthptr += (int)(code - last_code); DPRINTF(("length=%d added %d c=%c (0x%x)\n", *lengthptr, (int)(code - last_code), c, c)); /* If "previous" is set and it is not at the start of the work space, move it back to there, in order to avoid filling up the work space. Otherwise, if "previous" is NULL, reset the current code pointer to the start. */ if (previous != NULL) { if (previous > orig_code) { memmove(orig_code, previous, IN_UCHARS(code - previous)); code -= previous - orig_code; previous = orig_code; } } else code = orig_code; /* Remember where this code item starts so we can pick up the length next time round. */ last_code = code; } /* In the real compile phase, just check the workspace used by the forward reference list. */ else if (cd->hwm > cd->start_workspace + cd->workspace_size) { *errorcodeptr = ERR52; goto FAILED; } /* If in \Q...\E, check for the end; if not, we have a literal. Otherwise an isolated \E is ignored. */ if (c != CHAR_NULL) { if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E) { inescq = FALSE; ptr++; continue; } else if (inescq) { if (previous_callout != NULL) { if (lengthptr == NULL) /* Don't attempt in pre-compile phase */ complete_callout(previous_callout, ptr, cd); previous_callout = NULL; } if ((options & PCRE_AUTO_CALLOUT) != 0) { previous_callout = code; code = auto_callout(code, ptr, cd); } goto NORMAL_CHAR; } /* Check for the start of a \Q...\E sequence. We must do this here rather than later in case it is immediately followed by \E, which turns it into a "do nothing" sequence. */ if (c == CHAR_BACKSLASH && ptr[1] == CHAR_Q) { inescq = TRUE; ptr++; continue; } } /* In extended mode, skip white space and comments. */ if ((options & PCRE_EXTENDED) != 0) { const pcre_uchar *wscptr = ptr; while (MAX_255(c) && (cd->ctypes[c] & ctype_space) != 0) c = *(++ptr); if (c == CHAR_NUMBER_SIGN) { ptr++; while (*ptr != CHAR_NULL) { if (IS_NEWLINE(ptr)) /* For non-fixed-length newline cases, */ { /* IS_NEWLINE sets cd->nllen. */ ptr += cd->nllen; break; } ptr++; #ifdef SUPPORT_UTF if (utf) FORWARDCHAR(ptr); #endif } } /* If we skipped any characters, restart the loop. Otherwise, we didn't see a comment. */ if (ptr > wscptr) goto REDO_LOOP; } /* Skip over (?# comments. We need to do this here because we want to know if the next thing is a quantifier, and these comments may come between an item and its quantifier. */ if (c == CHAR_LEFT_PARENTHESIS && ptr[1] == CHAR_QUESTION_MARK && ptr[2] == CHAR_NUMBER_SIGN) { ptr += 3; while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; if (*ptr == CHAR_NULL) { *errorcodeptr = ERR18; goto FAILED; } continue; } /* See if the next thing is a quantifier. */ is_quantifier = c == CHAR_ASTERISK || c == CHAR_PLUS || c == CHAR_QUESTION_MARK || (c == CHAR_LEFT_CURLY_BRACKET && is_counted_repeat(ptr+1)); /* Fill in length of a previous callout, except when the next thing is a quantifier or when processing a property substitution string in UCP mode. */ if (!is_quantifier && previous_callout != NULL && nestptr == NULL && after_manual_callout-- <= 0) { if (lengthptr == NULL) /* Don't attempt in pre-compile phase */ complete_callout(previous_callout, ptr, cd); previous_callout = NULL; } /* Create auto callout, except for quantifiers, or while processing property strings that are substituted for \w etc in UCP mode. */ if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier && nestptr == NULL) { previous_callout = code; code = auto_callout(code, ptr, cd); } /* Process the next pattern item. */ switch(c) { /* ===================================================================*/ case CHAR_NULL: /* The branch terminates at string end */ case CHAR_VERTICAL_LINE: /* or | or ) */ case CHAR_RIGHT_PARENTHESIS: *firstcharptr = firstchar; *firstcharflagsptr = firstcharflags; *reqcharptr = reqchar; *reqcharflagsptr = reqcharflags; *codeptr = code; *ptrptr = ptr; if (lengthptr != NULL) { if (OFLOW_MAX - *lengthptr < code - last_code) { *errorcodeptr = ERR20; goto FAILED; } *lengthptr += (int)(code - last_code); /* To include callout length */ DPRINTF((">> end branch\n")); } return TRUE; /* ===================================================================*/ /* Handle single-character metacharacters. In multiline mode, ^ disables the setting of any following char as a first character. */ case CHAR_CIRCUMFLEX_ACCENT: previous = NULL; if ((options & PCRE_MULTILINE) != 0) { if (firstcharflags == REQ_UNSET) zerofirstcharflags = firstcharflags = REQ_NONE; *code++ = OP_CIRCM; } else *code++ = OP_CIRC; break; case CHAR_DOLLAR_SIGN: previous = NULL; *code++ = ((options & PCRE_MULTILINE) != 0)? OP_DOLLM : OP_DOLL; break; /* There can never be a first char if '.' is first, whatever happens about repeats. The value of reqchar doesn't change either. */ case CHAR_DOT: if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; *code++ = ((options & PCRE_DOTALL) != 0)? OP_ALLANY: OP_ANY; break; /* ===================================================================*/ /* Character classes. If the included characters are all < 256, we build a 32-byte bitmap of the permitted characters, except in the special case where there is only one such character. For negated classes, we build the map as usual, then invert it at the end. However, we use a different opcode so that data characters > 255 can be handled correctly. If the class contains characters outside the 0-255 range, a different opcode is compiled. It may optionally have a bit map for characters < 256, but those above are are explicitly listed afterwards. A flag byte tells whether the bitmap is present, and whether this is a negated class or not. In JavaScript compatibility mode, an isolated ']' causes an error. In default (Perl) mode, it is treated as a data character. */ case CHAR_RIGHT_SQUARE_BRACKET: if ((cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0) { *errorcodeptr = ERR64; goto FAILED; } goto NORMAL_CHAR; /* In another (POSIX) regex library, the ugly syntax [[:<:]] and [[:>:]] is used for "start of word" and "end of word". As these are otherwise illegal sequences, we don't break anything by recognizing them. They are replaced by \b(?=\w) and \b(?<=\w) respectively. Sequences like [a[:<:]] are erroneous and are handled by the normal code below. */ case CHAR_LEFT_SQUARE_BRACKET: if (STRNCMP_UC_C8(ptr+1, STRING_WEIRD_STARTWORD, 6) == 0) { nestptr = ptr + 7; ptr = sub_start_of_word; goto REDO_LOOP; } if (STRNCMP_UC_C8(ptr+1, STRING_WEIRD_ENDWORD, 6) == 0) { nestptr = ptr + 7; ptr = sub_end_of_word; goto REDO_LOOP; } /* Handle a real character class. */ previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; /* PCRE supports POSIX class stuff inside a class. Perl gives an error if they are encountered at the top level, so we'll do that too. */ if ((ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr)) { *errorcodeptr = (ptr[1] == CHAR_COLON)? ERR13 : ERR31; goto FAILED; } /* If the first character is '^', set the negation flag and skip it. Also, if the first few characters (either before or after ^) are \Q\E or \E we skip them too. This makes for compatibility with Perl. */ negate_class = FALSE; for (;;) { c = *(++ptr); if (c == CHAR_BACKSLASH) { if (ptr[1] == CHAR_E) ptr++; else if (STRNCMP_UC_C8(ptr + 1, STR_Q STR_BACKSLASH STR_E, 3) == 0) ptr += 3; else break; } else if (!negate_class && c == CHAR_CIRCUMFLEX_ACCENT) negate_class = TRUE; else break; } /* Empty classes are allowed in JavaScript compatibility mode. Otherwise, an initial ']' is taken as a data character -- the code below handles that. In JS mode, [] must always fail, so generate OP_FAIL, whereas [^] must match any character, so generate OP_ALLANY. */ if (c == CHAR_RIGHT_SQUARE_BRACKET && (cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0) { *code++ = negate_class? OP_ALLANY : OP_FAIL; if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; break; } /* If a class contains a negative special such as \S, we need to flip the negation flag at the end, so that support for characters > 255 works correctly (they are all included in the class). */ should_flip_negation = FALSE; /* Extended class (xclass) will be used when characters > 255 might match. */ #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 xclass = FALSE; class_uchardata = code + LINK_SIZE + 2; /* For XCLASS items */ class_uchardata_base = class_uchardata; /* Save the start */ #endif /* For optimization purposes, we track some properties of the class: class_has_8bitchar will be non-zero if the class contains at least one < 256 character; class_one_char will be 1 if the class contains just one character; xclass_has_prop will be TRUE if unicode property checks are present in the class. */ class_has_8bitchar = 0; class_one_char = 0; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 xclass_has_prop = FALSE; #endif /* Initialize the 32-char bit map to all zeros. We build the map in a temporary bit of memory, in case the class contains fewer than two 8-bit characters because in that case the compiled code doesn't use the bit map. */ memset(classbits, 0, 32 * sizeof(pcre_uint8)); /* Process characters until ] is reached. By writing this as a "do" it means that an initial ] is taken as a data character. At the start of the loop, c contains the first byte of the character. */ if (c != CHAR_NULL) do { const pcre_uchar *oldptr; #ifdef SUPPORT_UTF if (utf && HAS_EXTRALEN(c)) { /* Braces are required because the */ GETCHARLEN(c, ptr, ptr); /* macro generates multiple statements */ } #endif #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 /* In the pre-compile phase, accumulate the length of any extra data and reset the pointer. This is so that very large classes that contain a zillion > 255 characters no longer overwrite the work space (which is on the stack). We have to remember that there was XCLASS data, however. */ if (class_uchardata > class_uchardata_base) xclass = TRUE; if (lengthptr != NULL && class_uchardata > class_uchardata_base) { *lengthptr += (int)(class_uchardata - class_uchardata_base); class_uchardata = class_uchardata_base; } #endif /* Inside \Q...\E everything is literal except \E */ if (inescq) { if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E) /* If we are at \E */ { inescq = FALSE; /* Reset literal state */ ptr++; /* Skip the 'E' */ continue; /* Carry on with next */ } goto CHECK_RANGE; /* Could be range if \E follows */ } /* Handle POSIX class names. Perl allows a negation extension of the form [:^name:]. A square bracket that doesn't match the syntax is treated as a literal. We also recognize the POSIX constructions [.ch.] and [=ch=] ("collating elements") and fault them, as Perl 5.6 and 5.8 do. */ if (c == CHAR_LEFT_SQUARE_BRACKET && (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr)) { BOOL local_negate = FALSE; int posix_class, taboffset, tabopt; register const pcre_uint8 *cbits = cd->cbits; pcre_uint8 pbits[32]; if (ptr[1] != CHAR_COLON) { *errorcodeptr = ERR31; goto FAILED; } ptr += 2; if (*ptr == CHAR_CIRCUMFLEX_ACCENT) { local_negate = TRUE; should_flip_negation = TRUE; /* Note negative special */ ptr++; } posix_class = check_posix_name(ptr, (int)(tempptr - ptr)); if (posix_class < 0) { *errorcodeptr = ERR30; goto FAILED; } /* If matching is caseless, upper and lower are converted to alpha. This relies on the fact that the class table starts with alpha, lower, upper as the first 3 entries. */ if ((options & PCRE_CASELESS) != 0 && posix_class <= 2) posix_class = 0; /* When PCRE_UCP is set, some of the POSIX classes are converted to different escape sequences that use Unicode properties \p or \P. Others that are not available via \p or \P generate XCL_PROP/XCL_NOTPROP directly. */ #ifdef SUPPORT_UCP if ((options & PCRE_UCP) != 0) { unsigned int ptype = 0; int pc = posix_class + ((local_negate)? POSIX_SUBSIZE/2 : 0); /* The posix_substitutes table specifies which POSIX classes can be converted to \p or \P items. */ if (posix_substitutes[pc] != NULL) { nestptr = tempptr + 1; ptr = posix_substitutes[pc] - 1; continue; } /* There are three other classes that generate special property calls that are recognized only in an XCLASS. */ else switch(posix_class) { case PC_GRAPH: ptype = PT_PXGRAPH; /* Fall through */ case PC_PRINT: if (ptype == 0) ptype = PT_PXPRINT; /* Fall through */ case PC_PUNCT: if (ptype == 0) ptype = PT_PXPUNCT; *class_uchardata++ = local_negate? XCL_NOTPROP : XCL_PROP; *class_uchardata++ = ptype; *class_uchardata++ = 0; xclass_has_prop = TRUE; ptr = tempptr + 1; continue; /* For the other POSIX classes (ascii, cntrl, xdigit) we are going to fall through to the non-UCP case and build a bit map for characters with code points less than 256. If we are in a negated POSIX class, characters with code points greater than 255 must either all match or all not match. In the special case where we have not yet generated any xclass data, and this is the final item in the overall class, we need do nothing: later on, the opcode OP_NCLASS will be used to indicate that characters greater than 255 are acceptable. If we have already seen an xclass item or one may follow (we have to assume that it might if this is not the end of the class), explicitly list all wide codepoints, which will then either not match or match, depending on whether the class is or is not negated. */ default: if (local_negate && (xclass || tempptr[2] != CHAR_RIGHT_SQUARE_BRACKET)) { *class_uchardata++ = XCL_RANGE; class_uchardata += PRIV(ord2utf)(0x100, class_uchardata); class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata); } break; } } #endif /* In the non-UCP case, or when UCP makes no difference, we build the bit map for the POSIX class in a chunk of local store because we may be adding and subtracting from it, and we don't want to subtract bits that may be in the main map already. At the end we or the result into the bit map that is being built. */ posix_class *= 3; /* Copy in the first table (always present) */ memcpy(pbits, cbits + posix_class_maps[posix_class], 32 * sizeof(pcre_uint8)); /* If there is a second table, add or remove it as required. */ taboffset = posix_class_maps[posix_class + 1]; tabopt = posix_class_maps[posix_class + 2]; if (taboffset >= 0) { if (tabopt >= 0) for (c = 0; c < 32; c++) pbits[c] |= cbits[c + taboffset]; else for (c = 0; c < 32; c++) pbits[c] &= ~cbits[c + taboffset]; } /* Now see if we need to remove any special characters. An option value of 1 removes vertical space and 2 removes underscore. */ if (tabopt < 0) tabopt = -tabopt; if (tabopt == 1) pbits[1] &= ~0x3c; else if (tabopt == 2) pbits[11] &= 0x7f; /* Add the POSIX table or its complement into the main table that is being built and we are done. */ if (local_negate) for (c = 0; c < 32; c++) classbits[c] |= ~pbits[c]; else for (c = 0; c < 32; c++) classbits[c] |= pbits[c]; ptr = tempptr + 1; /* Every class contains at least one < 256 character. */ class_has_8bitchar = 1; /* Every class contains at least two characters. */ class_one_char = 2; continue; /* End of POSIX syntax handling */ } /* Backslash may introduce a single character, or it may introduce one of the specials, which just set a flag. The sequence \b is a special case. Inside a class (and only there) it is treated as backspace. We assume that other escapes have more than one character in them, so speculatively set both class_has_8bitchar and class_one_char bigger than one. Unrecognized escapes fall through and are either treated as literal characters (by default), or are faulted if PCRE_EXTRA is set. */ if (c == CHAR_BACKSLASH) { escape = check_escape(&ptr, &ec, errorcodeptr, cd->bracount, options, TRUE); if (*errorcodeptr != 0) goto FAILED; if (escape == 0) c = ec; else if (escape == ESC_b) c = CHAR_BS; /* \b is backspace in a class */ else if (escape == ESC_N) /* \N is not supported in a class */ { *errorcodeptr = ERR71; goto FAILED; } else if (escape == ESC_Q) /* Handle start of quoted string */ { if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) { ptr += 2; /* avoid empty string */ } else inescq = TRUE; continue; } else if (escape == ESC_E) continue; /* Ignore orphan \E */ else { register const pcre_uint8 *cbits = cd->cbits; /* Every class contains at least two < 256 characters. */ class_has_8bitchar++; /* Every class contains at least two characters. */ class_one_char += 2; switch (escape) { #ifdef SUPPORT_UCP case ESC_du: /* These are the values given for \d etc */ case ESC_DU: /* when PCRE_UCP is set. We replace the */ case ESC_wu: /* escape sequence with an appropriate \p */ case ESC_WU: /* or \P to test Unicode properties instead */ case ESC_su: /* of the default ASCII testing. */ case ESC_SU: nestptr = ptr; ptr = substitutes[escape - ESC_DU] - 1; /* Just before substitute */ class_has_8bitchar--; /* Undo! */ continue; #endif case ESC_d: for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit]; continue; case ESC_D: should_flip_negation = TRUE; for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit]; continue; case ESC_w: for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_word]; continue; case ESC_W: should_flip_negation = TRUE; for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word]; continue; /* Perl 5.004 onwards omitted VT from \s, but restored it at Perl 5.18. Before PCRE 8.34, we had to preserve the VT bit if it was previously set by something earlier in the character class. Luckily, the value of CHAR_VT is 0x0b in both ASCII and EBCDIC, so we could just adjust the appropriate bit. From PCRE 8.34 we no longer treat \s and \S specially. */ case ESC_s: for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_space]; continue; case ESC_S: should_flip_negation = TRUE; for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space]; continue; /* The rest apply in both UCP and non-UCP cases. */ case ESC_h: (void)add_list_to_class(classbits, &class_uchardata, options, cd, PRIV(hspace_list), NOTACHAR); continue; case ESC_H: (void)add_not_list_to_class(classbits, &class_uchardata, options, cd, PRIV(hspace_list)); continue; case ESC_v: (void)add_list_to_class(classbits, &class_uchardata, options, cd, PRIV(vspace_list), NOTACHAR); continue; case ESC_V: (void)add_not_list_to_class(classbits, &class_uchardata, options, cd, PRIV(vspace_list)); continue; case ESC_p: case ESC_P: #ifdef SUPPORT_UCP { BOOL negated; unsigned int ptype = 0, pdata = 0; if (!get_ucp(&ptr, &negated, &ptype, &pdata, errorcodeptr)) goto FAILED; *class_uchardata++ = ((escape == ESC_p) != negated)? XCL_PROP : XCL_NOTPROP; *class_uchardata++ = ptype; *class_uchardata++ = pdata; xclass_has_prop = TRUE; class_has_8bitchar--; /* Undo! */ continue; } #else *errorcodeptr = ERR45; goto FAILED; #endif /* Unrecognized escapes are faulted if PCRE is running in its strict mode. By default, for compatibility with Perl, they are treated as literals. */ default: if ((options & PCRE_EXTRA) != 0) { *errorcodeptr = ERR7; goto FAILED; } class_has_8bitchar--; /* Undo the speculative increase. */ class_one_char -= 2; /* Undo the speculative increase. */ c = *ptr; /* Get the final character and fall through */ break; } } /* Fall through if the escape just defined a single character (c >= 0). This may be greater than 256. */ escape = 0; } /* End of backslash handling */ /* A character may be followed by '-' to form a range. However, Perl does not permit ']' to be the end of the range. A '-' character at the end is treated as a literal. Perl ignores orphaned \E sequences entirely. The code for handling \Q and \E is messy. */ CHECK_RANGE: while (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) { inescq = FALSE; ptr += 2; } oldptr = ptr; /* Remember if \r or \n were explicitly used */ if (c == CHAR_CR || c == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; /* Check for range */ if (!inescq && ptr[1] == CHAR_MINUS) { pcre_uint32 d; ptr += 2; while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) ptr += 2; /* If we hit \Q (not followed by \E) at this point, go into escaped mode. */ while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_Q) { ptr += 2; if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) { ptr += 2; continue; } inescq = TRUE; break; } /* Minus (hyphen) at the end of a class is treated as a literal, so put back the pointer and jump to handle the character that preceded it. */ if (*ptr == CHAR_NULL || (!inescq && *ptr == CHAR_RIGHT_SQUARE_BRACKET)) { ptr = oldptr; goto CLASS_SINGLE_CHARACTER; } /* Otherwise, we have a potential range; pick up the next character */ #ifdef SUPPORT_UTF if (utf) { /* Braces are required because the */ GETCHARLEN(d, ptr, ptr); /* macro generates multiple statements */ } else #endif d = *ptr; /* Not UTF-8 mode */ /* The second part of a range can be a single-character escape sequence, but not any of the other escapes. Perl treats a hyphen as a literal in such circumstances. However, in Perl's warning mode, a warning is given, so PCRE now faults it as it is almost certainly a mistake on the user's part. */ if (!inescq) { if (d == CHAR_BACKSLASH) { int descape; descape = check_escape(&ptr, &d, errorcodeptr, cd->bracount, options, TRUE); if (*errorcodeptr != 0) goto FAILED; /* 0 means a character was put into d; \b is backspace; any other special causes an error. */ if (descape != 0) { if (descape == ESC_b) d = CHAR_BS; else { *errorcodeptr = ERR83; goto FAILED; } } } /* A hyphen followed by a POSIX class is treated in the same way. */ else if (d == CHAR_LEFT_SQUARE_BRACKET && (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr)) { *errorcodeptr = ERR83; goto FAILED; } } /* Check that the two values are in the correct order. Optimize one-character ranges. */ if (d < c) { *errorcodeptr = ERR8; goto FAILED; } if (d == c) goto CLASS_SINGLE_CHARACTER; /* A few lines below */ /* We have found a character range, so single character optimizations cannot be done anymore. Any value greater than 1 indicates that there is more than one character. */ class_one_char = 2; /* Remember an explicit \r or \n, and add the range to the class. */ if (d == CHAR_CR || d == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; class_has_8bitchar += add_to_class(classbits, &class_uchardata, options, cd, c, d); continue; /* Go get the next char in the class */ } /* Handle a single character - we can get here for a normal non-escape char, or after \ that introduces a single character or for an apparent range that isn't. Only the value 1 matters for class_one_char, so don't increase it if it is already 2 or more ... just in case there's a class with a zillion characters in it. */ CLASS_SINGLE_CHARACTER: if (class_one_char < 2) class_one_char++; /* If xclass_has_prop is false and class_one_char is 1, we have the first single character in the class, and there have been no prior ranges, or XCLASS items generated by escapes. If this is the final character in the class, we can optimize by turning the item into a 1-character OP_CHAR[I] if it's positive, or OP_NOT[I] if it's negative. In the positive case, it can cause firstchar to be set. Otherwise, there can be no first char if this item is first, whatever repeat count may follow. In the case of reqchar, save the previous value for reinstating. */ if (!inescq && #ifdef SUPPORT_UCP !xclass_has_prop && #endif class_one_char == 1 && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) { ptr++; zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; if (negate_class) { #ifdef SUPPORT_UCP int d; #endif if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; /* For caseless UTF-8 mode when UCP support is available, check whether this character has more than one other case. If so, generate a special OP_NOTPROP item instead of OP_NOTI. */ #ifdef SUPPORT_UCP if (utf && (options & PCRE_CASELESS) != 0 && (d = UCD_CASESET(c)) != 0) { *code++ = OP_NOTPROP; *code++ = PT_CLIST; *code++ = d; } else #endif /* Char has only one other case, or UCP not available */ { *code++ = ((options & PCRE_CASELESS) != 0)? OP_NOTI: OP_NOT; #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) code += PRIV(ord2utf)(c, code); else #endif *code++ = c; } /* We are finished with this character class */ goto END_CLASS; } /* For a single, positive character, get the value into mcbuffer, and then we can handle this with the normal one-character code. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) mclength = PRIV(ord2utf)(c, mcbuffer); else #endif { mcbuffer[0] = c; mclength = 1; } goto ONE_CHAR; } /* End of 1-char optimization */ /* There is more than one character in the class, or an XCLASS item has been generated. Add this character to the class. */ class_has_8bitchar += add_to_class(classbits, &class_uchardata, options, cd, c, c); } /* Loop until ']' reached. This "while" is the end of the "do" far above. If we are at the end of an internal nested string, revert to the outer string. */ while (((c = *(++ptr)) != CHAR_NULL || (nestptr != NULL && (ptr = nestptr, nestptr = NULL, c = *(++ptr)) != CHAR_NULL)) && (c != CHAR_RIGHT_SQUARE_BRACKET || inescq)); /* Check for missing terminating ']' */ if (c == CHAR_NULL) { *errorcodeptr = ERR6; goto FAILED; } /* We will need an XCLASS if data has been placed in class_uchardata. In the second phase this is a sufficient test. However, in the pre-compile phase, class_uchardata gets emptied to prevent workspace overflow, so it only if the very last character in the class needs XCLASS will it contain anything at this point. For this reason, xclass gets set TRUE above when uchar_classdata is emptied, and that's why this code is the way it is here instead of just doing a test on class_uchardata below. */ #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 if (class_uchardata > class_uchardata_base) xclass = TRUE; #endif /* If this is the first thing in the branch, there can be no first char setting, whatever the repeat count. Any reqchar setting must remain unchanged after any kind of repeat. */ if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; /* If there are characters with values > 255, we have to compile an extended class, with its own opcode, unless there was a negated special such as \S in the class, and PCRE_UCP is not set, because in that case all characters > 255 are in the class, so any that were explicitly given as well can be ignored. If (when there are explicit characters > 255 that must be listed) there are no characters < 256, we can omit the bitmap in the actual compiled code. */ #ifdef SUPPORT_UTF if (xclass && (xclass_has_prop || !should_flip_negation || (options & PCRE_UCP) != 0)) #elif !defined COMPILE_PCRE8 if (xclass && (xclass_has_prop || !should_flip_negation)) #endif #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 { /* For non-UCP wide characters, in a non-negative class containing \S or similar (should_flip_negation is set), all characters greater than 255 must be in the class. */ if ( #if defined COMPILE_PCRE8 utf && #endif should_flip_negation && !negate_class && (options & PCRE_UCP) == 0) { *class_uchardata++ = XCL_RANGE; if (utf) /* Will always be utf in the 8-bit library */ { class_uchardata += PRIV(ord2utf)(0x100, class_uchardata); class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata); } else /* Can only happen for the 16-bit & 32-bit libraries */ { #if defined COMPILE_PCRE16 *class_uchardata++ = 0x100; *class_uchardata++ = 0xffffu; #elif defined COMPILE_PCRE32 *class_uchardata++ = 0x100; *class_uchardata++ = 0xffffffffu; #endif } } *class_uchardata++ = XCL_END; /* Marks the end of extra data */ *code++ = OP_XCLASS; code += LINK_SIZE; *code = negate_class? XCL_NOT:0; if (xclass_has_prop) *code |= XCL_HASPROP; /* If the map is required, move up the extra data to make room for it; otherwise just move the code pointer to the end of the extra data. */ if (class_has_8bitchar > 0) { *code++ |= XCL_MAP; memmove(code + (32 / sizeof(pcre_uchar)), code, IN_UCHARS(class_uchardata - code)); if (negate_class && !xclass_has_prop) for (c = 0; c < 32; c++) classbits[c] = ~classbits[c]; memcpy(code, classbits, 32); code = class_uchardata + (32 / sizeof(pcre_uchar)); } else code = class_uchardata; /* Now fill in the complete length of the item */ PUT(previous, 1, (int)(code - previous)); break; /* End of class handling */ } /* Even though any XCLASS list is now discarded, we must allow for its memory. */ if (lengthptr != NULL) *lengthptr += (int)(class_uchardata - class_uchardata_base); #endif /* If there are no characters > 255, or they are all to be included or excluded, set the opcode to OP_CLASS or OP_NCLASS, depending on whether the whole class was negated and whether there were negative specials such as \S (non-UCP) in the class. Then copy the 32-byte map into the code vector, negating it if necessary. */ *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS; if (lengthptr == NULL) /* Save time in the pre-compile phase */ { if (negate_class) for (c = 0; c < 32; c++) classbits[c] = ~classbits[c]; memcpy(code, classbits, 32); } code += 32 / sizeof(pcre_uchar); END_CLASS: break; /* ===================================================================*/ /* Various kinds of repeat; '{' is not necessarily a quantifier, but this has been tested above. */ case CHAR_LEFT_CURLY_BRACKET: if (!is_quantifier) goto NORMAL_CHAR; ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorcodeptr); if (*errorcodeptr != 0) goto FAILED; goto REPEAT; case CHAR_ASTERISK: repeat_min = 0; repeat_max = -1; goto REPEAT; case CHAR_PLUS: repeat_min = 1; repeat_max = -1; goto REPEAT; case CHAR_QUESTION_MARK: repeat_min = 0; repeat_max = 1; REPEAT: if (previous == NULL) { *errorcodeptr = ERR9; goto FAILED; } if (repeat_min == 0) { firstchar = zerofirstchar; /* Adjust for zero repeat */ firstcharflags = zerofirstcharflags; reqchar = zeroreqchar; /* Ditto */ reqcharflags = zeroreqcharflags; } /* Remember whether this is a variable length repeat */ reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY; op_type = 0; /* Default single-char op codes */ possessive_quantifier = FALSE; /* Default not possessive quantifier */ /* Save start of previous item, in case we have to move it up in order to insert something before it. */ tempcode = previous; /* Before checking for a possessive quantifier, we must skip over whitespace and comments in extended mode because Perl allows white space at this point. */ if ((options & PCRE_EXTENDED) != 0) { const pcre_uchar *p = ptr + 1; for (;;) { while (MAX_255(*p) && (cd->ctypes[*p] & ctype_space) != 0) p++; if (*p != CHAR_NUMBER_SIGN) break; p++; while (*p != CHAR_NULL) { if (IS_NEWLINE(p)) /* For non-fixed-length newline cases, */ { /* IS_NEWLINE sets cd->nllen. */ p += cd->nllen; break; } p++; #ifdef SUPPORT_UTF if (utf) FORWARDCHAR(p); #endif } /* Loop for comment characters */ } /* Loop for multiple comments */ ptr = p - 1; /* Character before the next significant one. */ } /* We also need to skip over (?# comments, which are not dependent on extended mode. */ if (ptr[1] == CHAR_LEFT_PARENTHESIS && ptr[2] == CHAR_QUESTION_MARK && ptr[3] == CHAR_NUMBER_SIGN) { ptr += 4; while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; if (*ptr == CHAR_NULL) { *errorcodeptr = ERR18; goto FAILED; } } /* If the next character is '+', we have a possessive quantifier. This implies greediness, whatever the setting of the PCRE_UNGREEDY option. If the next character is '?' this is a minimizing repeat, by default, but if PCRE_UNGREEDY is set, it works the other way round. We change the repeat type to the non-default. */ if (ptr[1] == CHAR_PLUS) { repeat_type = 0; /* Force greedy */ possessive_quantifier = TRUE; ptr++; } else if (ptr[1] == CHAR_QUESTION_MARK) { repeat_type = greedy_non_default; ptr++; } else repeat_type = greedy_default; /* If previous was a recursion call, wrap it in atomic brackets so that previous becomes the atomic group. All recursions were so wrapped in the past, but it no longer happens for non-repeated recursions. In fact, the repeated ones could be re-implemented independently so as not to need this, but for the moment we rely on the code for repeating groups. */ if (*previous == OP_RECURSE) { memmove(previous + 1 + LINK_SIZE, previous, IN_UCHARS(1 + LINK_SIZE)); *previous = OP_ONCE; PUT(previous, 1, 2 + 2*LINK_SIZE); previous[2 + 2*LINK_SIZE] = OP_KET; PUT(previous, 3 + 2*LINK_SIZE, 2 + 2*LINK_SIZE); code += 2 + 2 * LINK_SIZE; length_prevgroup = 3 + 3*LINK_SIZE; /* When actually compiling, we need to check whether this was a forward reference, and if so, adjust the offset. */ if (lengthptr == NULL && cd->hwm >= cd->start_workspace + LINK_SIZE) { int offset = GET(cd->hwm, -LINK_SIZE); if (offset == previous + 1 - cd->start_code) PUT(cd->hwm, -LINK_SIZE, offset + 1 + LINK_SIZE); } } /* Now handle repetition for the different types of item. */ /* If previous was a character or negated character match, abolish the item and generate a repeat item instead. If a char item has a minimum of more than one, ensure that it is set in reqchar - it might not be if a sequence such as x{3} is the first thing in a branch because the x will have gone into firstchar instead. */ if (*previous == OP_CHAR || *previous == OP_CHARI || *previous == OP_NOT || *previous == OP_NOTI) { switch (*previous) { default: /* Make compiler happy. */ case OP_CHAR: op_type = OP_STAR - OP_STAR; break; case OP_CHARI: op_type = OP_STARI - OP_STAR; break; case OP_NOT: op_type = OP_NOTSTAR - OP_STAR; break; case OP_NOTI: op_type = OP_NOTSTARI - OP_STAR; break; } /* Deal with UTF characters that take up more than one character. It's easier to write this out separately than try to macrify it. Use c to hold the length of the character in bytes, plus UTF_LENGTH to flag that it's a length rather than a small character. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && NOT_FIRSTCHAR(code[-1])) { pcre_uchar *lastchar = code - 1; BACKCHAR(lastchar); c = (int)(code - lastchar); /* Length of UTF-8 character */ memcpy(utf_chars, lastchar, IN_UCHARS(c)); /* Save the char */ c |= UTF_LENGTH; /* Flag c as a length */ } else #endif /* SUPPORT_UTF */ /* Handle the case of a single charater - either with no UTF support, or with UTF disabled, or for a single character UTF character. */ { c = code[-1]; if (*previous <= OP_CHARI && repeat_min > 1) { reqchar = c; reqcharflags = req_caseopt | cd->req_varyopt; } } goto OUTPUT_SINGLE_REPEAT; /* Code shared with single character types */ } /* If previous was a character type match (\d or similar), abolish it and create a suitable repeat item. The code is shared with single-character repeats by setting op_type to add a suitable offset into repeat_type. Note the the Unicode property types will be present only when SUPPORT_UCP is defined, but we don't wrap the little bits of code here because it just makes it horribly messy. */ else if (*previous < OP_EODN) { pcre_uchar *oldcode; int prop_type, prop_value; op_type = OP_TYPESTAR - OP_STAR; /* Use type opcodes */ c = *previous; OUTPUT_SINGLE_REPEAT: if (*previous == OP_PROP || *previous == OP_NOTPROP) { prop_type = previous[1]; prop_value = previous[2]; } else prop_type = prop_value = -1; oldcode = code; code = previous; /* Usually overwrite previous item */ /* If the maximum is zero then the minimum must also be zero; Perl allows this case, so we do too - by simply omitting the item altogether. */ if (repeat_max == 0) goto END_REPEAT; /* Combine the op_type with the repeat_type */ repeat_type += op_type; /* A minimum of zero is handled either as the special case * or ?, or as an UPTO, with the maximum given. */ if (repeat_min == 0) { if (repeat_max == -1) *code++ = OP_STAR + repeat_type; else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type; else { *code++ = OP_UPTO + repeat_type; PUT2INC(code, 0, repeat_max); } } /* A repeat minimum of 1 is optimized into some special cases. If the maximum is unlimited, we use OP_PLUS. Otherwise, the original item is left in place and, if the maximum is greater than 1, we use OP_UPTO with one less than the maximum. */ else if (repeat_min == 1) { if (repeat_max == -1) *code++ = OP_PLUS + repeat_type; else { code = oldcode; /* leave previous item in place */ if (repeat_max == 1) goto END_REPEAT; *code++ = OP_UPTO + repeat_type; PUT2INC(code, 0, repeat_max - 1); } } /* The case {n,n} is just an EXACT, while the general case {n,m} is handled as an EXACT followed by an UPTO. */ else { *code++ = OP_EXACT + op_type; /* NB EXACT doesn't have repeat_type */ PUT2INC(code, 0, repeat_min); /* If the maximum is unlimited, insert an OP_STAR. Before doing so, we have to insert the character for the previous code. For a repeated Unicode property match, there are two extra bytes that define the required property. In UTF-8 mode, long characters have their length in c, with the UTF_LENGTH bit as a flag. */ if (repeat_max < 0) { #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && (c & UTF_LENGTH) != 0) { memcpy(code, utf_chars, IN_UCHARS(c & 7)); code += c & 7; } else #endif { *code++ = c; if (prop_type >= 0) { *code++ = prop_type; *code++ = prop_value; } } *code++ = OP_STAR + repeat_type; } /* Else insert an UPTO if the max is greater than the min, again preceded by the character, for the previously inserted code. If the UPTO is just for 1 instance, we can use QUERY instead. */ else if (repeat_max != repeat_min) { #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && (c & UTF_LENGTH) != 0) { memcpy(code, utf_chars, IN_UCHARS(c & 7)); code += c & 7; } else #endif *code++ = c; if (prop_type >= 0) { *code++ = prop_type; *code++ = prop_value; } repeat_max -= repeat_min; if (repeat_max == 1) { *code++ = OP_QUERY + repeat_type; } else { *code++ = OP_UPTO + repeat_type; PUT2INC(code, 0, repeat_max); } } } /* The character or character type itself comes last in all cases. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && (c & UTF_LENGTH) != 0) { memcpy(code, utf_chars, IN_UCHARS(c & 7)); code += c & 7; } else #endif *code++ = c; /* For a repeated Unicode property match, there are two extra bytes that define the required property. */ #ifdef SUPPORT_UCP if (prop_type >= 0) { *code++ = prop_type; *code++ = prop_value; } #endif } /* If previous was a character class or a back reference, we put the repeat stuff after it, but just skip the item if the repeat was {0,0}. */ else if (*previous == OP_CLASS || *previous == OP_NCLASS || #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 *previous == OP_XCLASS || #endif *previous == OP_REF || *previous == OP_REFI || *previous == OP_DNREF || *previous == OP_DNREFI) { if (repeat_max == 0) { code = previous; goto END_REPEAT; } if (repeat_min == 0 && repeat_max == -1) *code++ = OP_CRSTAR + repeat_type; else if (repeat_min == 1 && repeat_max == -1) *code++ = OP_CRPLUS + repeat_type; else if (repeat_min == 0 && repeat_max == 1) *code++ = OP_CRQUERY + repeat_type; else { *code++ = OP_CRRANGE + repeat_type; PUT2INC(code, 0, repeat_min); if (repeat_max == -1) repeat_max = 0; /* 2-byte encoding for max */ PUT2INC(code, 0, repeat_max); } } /* If previous was a bracket group, we may have to replicate it in certain cases. Note that at this point we can encounter only the "basic" bracket opcodes such as BRA and CBRA, as this is the place where they get converted into the more special varieties such as BRAPOS and SBRA. A test for >= OP_ASSERT and <= OP_COND includes ASSERT, ASSERT_NOT, ASSERTBACK, ASSERTBACK_NOT, ONCE, ONCE_NC, BRA, BRAPOS, CBRA, CBRAPOS, and COND. Originally, PCRE did not allow repetition of assertions, but now it does, for Perl compatibility. */ else if (*previous >= OP_ASSERT && *previous <= OP_COND) { register int i; int len = (int)(code - previous); size_t base_hwm_offset = item_hwm_offset; pcre_uchar *bralink = NULL; pcre_uchar *brazeroptr = NULL; /* Repeating a DEFINE group is pointless, but Perl allows the syntax, so we just ignore the repeat. */ if (*previous == OP_COND && previous[LINK_SIZE+1] == OP_DEF) goto END_REPEAT; /* There is no sense in actually repeating assertions. The only potential use of repetition is in cases when the assertion is optional. Therefore, if the minimum is greater than zero, just ignore the repeat. If the maximum is not zero or one, set it to 1. */ if (*previous < OP_ONCE) /* Assertion */ { if (repeat_min > 0) goto END_REPEAT; if (repeat_max < 0 || repeat_max > 1) repeat_max = 1; } /* The case of a zero minimum is special because of the need to stick OP_BRAZERO in front of it, and because the group appears once in the data, whereas in other cases it appears the minimum number of times. For this reason, it is simplest to treat this case separately, as otherwise the code gets far too messy. There are several special subcases when the minimum is zero. */ if (repeat_min == 0) { /* If the maximum is also zero, we used to just omit the group from the output altogether, like this: ** if (repeat_max == 0) ** { ** code = previous; ** goto END_REPEAT; ** } However, that fails when a group or a subgroup within it is referenced as a subroutine from elsewhere in the pattern, so now we stick in OP_SKIPZERO in front of it so that it is skipped on execution. As we don't have a list of which groups are referenced, we cannot do this selectively. If the maximum is 1 or unlimited, we just have to stick in the BRAZERO and do no more at this point. However, we do need to adjust any OP_RECURSE calls inside the group that refer to the group itself or any internal or forward referenced group, because the offset is from the start of the whole regex. Temporarily terminate the pattern while doing this. */ if (repeat_max <= 1) /* Covers 0, 1, and unlimited */ { *code = OP_END; adjust_recurse(previous, 1, utf, cd, item_hwm_offset); memmove(previous + 1, previous, IN_UCHARS(len)); code++; if (repeat_max == 0) { *previous++ = OP_SKIPZERO; goto END_REPEAT; } brazeroptr = previous; /* Save for possessive optimizing */ *previous++ = OP_BRAZERO + repeat_type; } /* If the maximum is greater than 1 and limited, we have to replicate in a nested fashion, sticking OP_BRAZERO before each set of brackets. The first one has to be handled carefully because it's the original copy, which has to be moved up. The remainder can be handled by code that is common with the non-zero minimum case below. We have to adjust the value or repeat_max, since one less copy is required. Once again, we may have to adjust any OP_RECURSE calls inside the group. */ else { int offset; *code = OP_END; adjust_recurse(previous, 2 + LINK_SIZE, utf, cd, item_hwm_offset); memmove(previous + 2 + LINK_SIZE, previous, IN_UCHARS(len)); code += 2 + LINK_SIZE; *previous++ = OP_BRAZERO + repeat_type; *previous++ = OP_BRA; /* We chain together the bracket offset fields that have to be filled in later when the ends of the brackets are reached. */ offset = (bralink == NULL)? 0 : (int)(previous - bralink); bralink = previous; PUTINC(previous, 0, offset); } repeat_max--; } /* If the minimum is greater than zero, replicate the group as many times as necessary, and adjust the maximum to the number of subsequent copies that we need. If we set a first char from the group, and didn't set a required char, copy the latter from the former. If there are any forward reference subroutine calls in the group, there will be entries on the workspace list; replicate these with an appropriate increment. */ else { if (repeat_min > 1) { /* In the pre-compile phase, we don't actually do the replication. We just adjust the length as if we had. Do some paranoid checks for potential integer overflow. The INT64_OR_DOUBLE type is a 64-bit integer type when available, otherwise double. */ if (lengthptr != NULL) { int delta = (repeat_min - 1)*length_prevgroup; if ((INT64_OR_DOUBLE)(repeat_min - 1)* (INT64_OR_DOUBLE)length_prevgroup > (INT64_OR_DOUBLE)INT_MAX || OFLOW_MAX - *lengthptr < delta) { *errorcodeptr = ERR20; goto FAILED; } *lengthptr += delta; } /* This is compiling for real. If there is a set first byte for the group, and we have not yet set a "required byte", set it. Make sure there is enough workspace for copying forward references before doing the copy. */ else { if (groupsetfirstchar && reqcharflags < 0) { reqchar = firstchar; reqcharflags = firstcharflags; } for (i = 1; i < repeat_min; i++) { pcre_uchar *hc; size_t this_hwm_offset = cd->hwm - cd->start_workspace; memcpy(code, previous, IN_UCHARS(len)); while (cd->hwm > cd->start_workspace + cd->workspace_size - WORK_SIZE_SAFETY_MARGIN - (this_hwm_offset - base_hwm_offset)) { *errorcodeptr = expand_workspace(cd); if (*errorcodeptr != 0) goto FAILED; } for (hc = (pcre_uchar *)cd->start_workspace + base_hwm_offset; hc < (pcre_uchar *)cd->start_workspace + this_hwm_offset; hc += LINK_SIZE) { PUT(cd->hwm, 0, GET(hc, 0) + len); cd->hwm += LINK_SIZE; } base_hwm_offset = this_hwm_offset; code += len; } } } if (repeat_max > 0) repeat_max -= repeat_min; } /* This code is common to both the zero and non-zero minimum cases. If the maximum is limited, it replicates the group in a nested fashion, remembering the bracket starts on a stack. In the case of a zero minimum, the first one was set up above. In all cases the repeat_max now specifies the number of additional copies needed. Again, we must remember to replicate entries on the forward reference list. */ if (repeat_max >= 0) { /* In the pre-compile phase, we don't actually do the replication. We just adjust the length as if we had. For each repetition we must add 1 to the length for BRAZERO and for all but the last repetition we must add 2 + 2*LINKSIZE to allow for the nesting that occurs. Do some paranoid checks to avoid integer overflow. The INT64_OR_DOUBLE type is a 64-bit integer type when available, otherwise double. */ if (lengthptr != NULL && repeat_max > 0) { int delta = repeat_max * (length_prevgroup + 1 + 2 + 2*LINK_SIZE) - 2 - 2*LINK_SIZE; /* Last one doesn't nest */ if ((INT64_OR_DOUBLE)repeat_max * (INT64_OR_DOUBLE)(length_prevgroup + 1 + 2 + 2*LINK_SIZE) > (INT64_OR_DOUBLE)INT_MAX || OFLOW_MAX - *lengthptr < delta) { *errorcodeptr = ERR20; goto FAILED; } *lengthptr += delta; } /* This is compiling for real */ else for (i = repeat_max - 1; i >= 0; i--) { pcre_uchar *hc; size_t this_hwm_offset = cd->hwm - cd->start_workspace; *code++ = OP_BRAZERO + repeat_type; /* All but the final copy start a new nesting, maintaining the chain of brackets outstanding. */ if (i != 0) { int offset; *code++ = OP_BRA; offset = (bralink == NULL)? 0 : (int)(code - bralink); bralink = code; PUTINC(code, 0, offset); } memcpy(code, previous, IN_UCHARS(len)); /* Ensure there is enough workspace for forward references before copying them. */ while (cd->hwm > cd->start_workspace + cd->workspace_size - WORK_SIZE_SAFETY_MARGIN - (this_hwm_offset - base_hwm_offset)) { *errorcodeptr = expand_workspace(cd); if (*errorcodeptr != 0) goto FAILED; } for (hc = (pcre_uchar *)cd->start_workspace + base_hwm_offset; hc < (pcre_uchar *)cd->start_workspace + this_hwm_offset; hc += LINK_SIZE) { PUT(cd->hwm, 0, GET(hc, 0) + len + ((i != 0)? 2+LINK_SIZE : 1)); cd->hwm += LINK_SIZE; } base_hwm_offset = this_hwm_offset; code += len; } /* Now chain through the pending brackets, and fill in their length fields (which are holding the chain links pro tem). */ while (bralink != NULL) { int oldlinkoffset; int offset = (int)(code - bralink + 1); pcre_uchar *bra = code - offset; oldlinkoffset = GET(bra, 1); bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset; *code++ = OP_KET; PUTINC(code, 0, offset); PUT(bra, 1, offset); } } /* If the maximum is unlimited, set a repeater in the final copy. For ONCE brackets, that's all we need to do. However, possessively repeated ONCE brackets can be converted into non-capturing brackets, as the behaviour of (?:xx)++ is the same as (?>xx)++ and this saves having to deal with possessive ONCEs specially. Otherwise, when we are doing the actual compile phase, check to see whether this group is one that could match an empty string. If so, convert the initial operator to the S form (e.g. OP_BRA -> OP_SBRA) so that runtime checking can be done. [This check is also applied to ONCE groups at runtime, but in a different way.] Then, if the quantifier was possessive and the bracket is not a conditional, we convert the BRA code to the POS form, and the KET code to KETRPOS. (It turns out to be convenient at runtime to detect this kind of subpattern at both the start and at the end.) The use of special opcodes makes it possible to reduce greatly the stack usage in pcre_exec(). If the group is preceded by OP_BRAZERO, convert this to OP_BRAPOSZERO. Then, if the minimum number of matches is 1 or 0, cancel the possessive flag so that the default action below, of wrapping everything inside atomic brackets, does not happen. When the minimum is greater than 1, there will be earlier copies of the group, and so we still have to wrap the whole thing. */ else { pcre_uchar *ketcode = code - 1 - LINK_SIZE; pcre_uchar *bracode = ketcode - GET(ketcode, 1); /* Convert possessive ONCE brackets to non-capturing */ if ((*bracode == OP_ONCE || *bracode == OP_ONCE_NC) && possessive_quantifier) *bracode = OP_BRA; /* For non-possessive ONCE brackets, all we need to do is to set the KET. */ if (*bracode == OP_ONCE || *bracode == OP_ONCE_NC) *ketcode = OP_KETRMAX + repeat_type; /* Handle non-ONCE brackets and possessive ONCEs (which have been converted to non-capturing above). */ else { /* In the compile phase, check for empty string matching. */ if (lengthptr == NULL) { pcre_uchar *scode = bracode; do { if (could_be_empty_branch(scode, ketcode, utf, cd, NULL)) { *bracode += OP_SBRA - OP_BRA; break; } scode += GET(scode, 1); } while (*scode == OP_ALT); } /* A conditional group with only one branch has an implicit empty alternative branch. */ if (*bracode == OP_COND && bracode[GET(bracode,1)] != OP_ALT) *bracode = OP_SCOND; /* Handle possessive quantifiers. */ if (possessive_quantifier) { /* For COND brackets, we wrap the whole thing in a possessively repeated non-capturing bracket, because we have not invented POS versions of the COND opcodes. Because we are moving code along, we must ensure that any pending recursive references are updated. */ if (*bracode == OP_COND || *bracode == OP_SCOND) { int nlen = (int)(code - bracode); *code = OP_END; adjust_recurse(bracode, 1 + LINK_SIZE, utf, cd, item_hwm_offset); memmove(bracode + 1 + LINK_SIZE, bracode, IN_UCHARS(nlen)); code += 1 + LINK_SIZE; nlen += 1 + LINK_SIZE; *bracode = (*bracode == OP_COND)? OP_BRAPOS : OP_SBRAPOS; *code++ = OP_KETRPOS; PUTINC(code, 0, nlen); PUT(bracode, 1, nlen); } /* For non-COND brackets, we modify the BRA code and use KETRPOS. */ else { *bracode += 1; /* Switch to xxxPOS opcodes */ *ketcode = OP_KETRPOS; } /* If the minimum is zero, mark it as possessive, then unset the possessive flag when the minimum is 0 or 1. */ if (brazeroptr != NULL) *brazeroptr = OP_BRAPOSZERO; if (repeat_min < 2) possessive_quantifier = FALSE; } /* Non-possessive quantifier */ else *ketcode = OP_KETRMAX + repeat_type; } } } /* If previous is OP_FAIL, it was generated by an empty class [] in JavaScript mode. The other ways in which OP_FAIL can be generated, that is by (*FAIL) or (?!) set previous to NULL, which gives a "nothing to repeat" error above. We can just ignore the repeat in JS case. */ else if (*previous == OP_FAIL) goto END_REPEAT; /* Else there's some kind of shambles */ else { *errorcodeptr = ERR11; goto FAILED; } /* If the character following a repeat is '+', possessive_quantifier is TRUE. For some opcodes, there are special alternative opcodes for this case. For anything else, we wrap the entire repeated item inside OP_ONCE brackets. Logically, the '+' notation is just syntactic sugar, taken from Sun's Java package, but the special opcodes can optimize it. Some (but not all) possessively repeated subpatterns have already been completely handled in the code just above. For them, possessive_quantifier is always FALSE at this stage. Note that the repeated item starts at tempcode, not at previous, which might be the first part of a string whose (former) last char we repeated. */ if (possessive_quantifier) { int len; /* Possessifying an EXACT quantifier has no effect, so we can ignore it. However, QUERY, STAR, or UPTO may follow (for quantifiers such as {5,6}, {5,}, or {5,10}). We skip over an EXACT item; if the length of what remains is greater than zero, there's a further opcode that can be handled. If not, do nothing, leaving the EXACT alone. */ switch(*tempcode) { case OP_TYPEEXACT: tempcode += PRIV(OP_lengths)[*tempcode] + ((tempcode[1 + IMM2_SIZE] == OP_PROP || tempcode[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0); break; /* CHAR opcodes are used for exacts whose count is 1. */ case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_EXACT: case OP_EXACTI: case OP_NOTEXACT: case OP_NOTEXACTI: tempcode += PRIV(OP_lengths)[*tempcode]; #ifdef SUPPORT_UTF if (utf && HAS_EXTRALEN(tempcode[-1])) tempcode += GET_EXTRALEN(tempcode[-1]); #endif break; /* For the class opcodes, the repeat operator appears at the end; adjust tempcode to point to it. */ case OP_CLASS: case OP_NCLASS: tempcode += 1 + 32/sizeof(pcre_uchar); break; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: tempcode += GET(tempcode, 1); break; #endif } /* If tempcode is equal to code (which points to the end of the repeated item), it means we have skipped an EXACT item but there is no following QUERY, STAR, or UPTO; the value of len will be 0, and we do nothing. In all other cases, tempcode will be pointing to the repeat opcode, and will be less than code, so the value of len will be greater than 0. */ len = (int)(code - tempcode); if (len > 0) { unsigned int repcode = *tempcode; /* There is a table for possessifying opcodes, all of which are less than OP_CALLOUT. A zero entry means there is no possessified version. */ if (repcode < OP_CALLOUT && opcode_possessify[repcode] > 0) *tempcode = opcode_possessify[repcode]; /* For opcode without a special possessified version, wrap the item in ONCE brackets. Because we are moving code along, we must ensure that any pending recursive references are updated. */ else { *code = OP_END; adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, item_hwm_offset); memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len)); code += 1 + LINK_SIZE; len += 1 + LINK_SIZE; tempcode[0] = OP_ONCE; *code++ = OP_KET; PUTINC(code, 0, len); PUT(tempcode, 1, len); } } #ifdef NEVER if (len > 0) switch (*tempcode) { case OP_STAR: *tempcode = OP_POSSTAR; break; case OP_PLUS: *tempcode = OP_POSPLUS; break; case OP_QUERY: *tempcode = OP_POSQUERY; break; case OP_UPTO: *tempcode = OP_POSUPTO; break; case OP_STARI: *tempcode = OP_POSSTARI; break; case OP_PLUSI: *tempcode = OP_POSPLUSI; break; case OP_QUERYI: *tempcode = OP_POSQUERYI; break; case OP_UPTOI: *tempcode = OP_POSUPTOI; break; case OP_NOTSTAR: *tempcode = OP_NOTPOSSTAR; break; case OP_NOTPLUS: *tempcode = OP_NOTPOSPLUS; break; case OP_NOTQUERY: *tempcode = OP_NOTPOSQUERY; break; case OP_NOTUPTO: *tempcode = OP_NOTPOSUPTO; break; case OP_NOTSTARI: *tempcode = OP_NOTPOSSTARI; break; case OP_NOTPLUSI: *tempcode = OP_NOTPOSPLUSI; break; case OP_NOTQUERYI: *tempcode = OP_NOTPOSQUERYI; break; case OP_NOTUPTOI: *tempcode = OP_NOTPOSUPTOI; break; case OP_TYPESTAR: *tempcode = OP_TYPEPOSSTAR; break; case OP_TYPEPLUS: *tempcode = OP_TYPEPOSPLUS; break; case OP_TYPEQUERY: *tempcode = OP_TYPEPOSQUERY; break; case OP_TYPEUPTO: *tempcode = OP_TYPEPOSUPTO; break; case OP_CRSTAR: *tempcode = OP_CRPOSSTAR; break; case OP_CRPLUS: *tempcode = OP_CRPOSPLUS; break; case OP_CRQUERY: *tempcode = OP_CRPOSQUERY; break; case OP_CRRANGE: *tempcode = OP_CRPOSRANGE; break; /* Because we are moving code along, we must ensure that any pending recursive references are updated. */ default: *code = OP_END; adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, item_hwm_offset); memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len)); code += 1 + LINK_SIZE; len += 1 + LINK_SIZE; tempcode[0] = OP_ONCE; *code++ = OP_KET; PUTINC(code, 0, len); PUT(tempcode, 1, len); break; } #endif } /* In all case we no longer have a previous item. We also set the "follows varying string" flag for subsequently encountered reqchars if it isn't already set and we have just passed a varying length item. */ END_REPEAT: previous = NULL; cd->req_varyopt |= reqvary; break; /* ===================================================================*/ /* Start of nested parenthesized sub-expression, or comment or lookahead or lookbehind or option setting or condition or all the other extended parenthesis forms. */ case CHAR_LEFT_PARENTHESIS: ptr++; /* Now deal with various "verbs" that can be introduced by '*'. */ if (ptr[0] == CHAR_ASTERISK && (ptr[1] == ':' || (MAX_255(ptr[1]) && ((cd->ctypes[ptr[1]] & ctype_letter) != 0)))) { int i, namelen; int arglen = 0; const char *vn = verbnames; const pcre_uchar *name = ptr + 1; const pcre_uchar *arg = NULL; previous = NULL; ptr++; while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_letter) != 0) ptr++; namelen = (int)(ptr - name); /* It appears that Perl allows any characters whatsoever, other than a closing parenthesis, to appear in arguments, so we no longer insist on letters, digits, and underscores. */ if (*ptr == CHAR_COLON) { arg = ++ptr; while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; arglen = (int)(ptr - arg); if ((unsigned int)arglen > MAX_MARK) { *errorcodeptr = ERR75; goto FAILED; } } if (*ptr != CHAR_RIGHT_PARENTHESIS) { *errorcodeptr = ERR60; goto FAILED; } /* Scan the table of verb names */ for (i = 0; i < verbcount; i++) { if (namelen == verbs[i].len && STRNCMP_UC_C8(name, vn, namelen) == 0) { int setverb; /* Check for open captures before ACCEPT and convert it to ASSERT_ACCEPT if in an assertion. */ if (verbs[i].op == OP_ACCEPT) { open_capitem *oc; if (arglen != 0) { *errorcodeptr = ERR59; goto FAILED; } cd->had_accept = TRUE; for (oc = cd->open_caps; oc != NULL; oc = oc->next) { if (lengthptr != NULL) { #ifdef COMPILE_PCRE8 *lengthptr += 1 + IMM2_SIZE; #elif defined COMPILE_PCRE16 *lengthptr += 2 + IMM2_SIZE; #elif defined COMPILE_PCRE32 *lengthptr += 4 + IMM2_SIZE; #endif } else { *code++ = OP_CLOSE; PUT2INC(code, 0, oc->number); } } setverb = *code++ = (cd->assert_depth > 0)? OP_ASSERT_ACCEPT : OP_ACCEPT; /* Do not set firstchar after *ACCEPT */ if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; } /* Handle other cases with/without an argument */ else if (arglen == 0) { if (verbs[i].op < 0) /* Argument is mandatory */ { *errorcodeptr = ERR66; goto FAILED; } setverb = *code++ = verbs[i].op; } else { if (verbs[i].op_arg < 0) /* Argument is forbidden */ { *errorcodeptr = ERR59; goto FAILED; } setverb = *code++ = verbs[i].op_arg; if (lengthptr != NULL) /* In pass 1 just add in the length */ { /* to avoid potential workspace */ *lengthptr += arglen; /* overflow. */ *code++ = 0; } else { *code++ = arglen; memcpy(code, arg, IN_UCHARS(arglen)); code += arglen; } *code++ = 0; } switch (setverb) { case OP_THEN: case OP_THEN_ARG: cd->external_flags |= PCRE_HASTHEN; break; case OP_PRUNE: case OP_PRUNE_ARG: case OP_SKIP: case OP_SKIP_ARG: cd->had_pruneorskip = TRUE; break; } break; /* Found verb, exit loop */ } vn += verbs[i].len + 1; } if (i < verbcount) continue; /* Successfully handled a verb */ *errorcodeptr = ERR60; /* Verb not recognized */ goto FAILED; } /* Initialize for "real" parentheses */ newoptions = options; skipbytes = 0; bravalue = OP_CBRA; item_hwm_offset = cd->hwm - cd->start_workspace; reset_bracount = FALSE; /* Deal with the extended parentheses; all are introduced by '?', and the appearance of any of them means that this is not a capturing group. */ if (*ptr == CHAR_QUESTION_MARK) { int i, set, unset, namelen; int *optset; const pcre_uchar *name; pcre_uchar *slot; switch (*(++ptr)) { /* ------------------------------------------------------------ */ case CHAR_VERTICAL_LINE: /* Reset capture count for each branch */ reset_bracount = TRUE; cd->dupgroups = TRUE; /* Record (?| encountered */ /* Fall through */ /* ------------------------------------------------------------ */ case CHAR_COLON: /* Non-capturing bracket */ bravalue = OP_BRA; ptr++; break; /* ------------------------------------------------------------ */ case CHAR_LEFT_PARENTHESIS: bravalue = OP_COND; /* Conditional group */ tempptr = ptr; /* A condition can be an assertion, a number (referring to a numbered group's having been set), a name (referring to a named group), or 'R', referring to recursion. R<digits> and R&name are also permitted for recursion tests. There are ways of testing a named group: (?(name)) is used by Python; Perl 5.10 onwards uses (?(<name>) or (?('name')). There is one unfortunate ambiguity, caused by history. 'R' can be the recursive thing or the name 'R' (and similarly for 'R' followed by digits). We look for a name first; if not found, we try the other case. For compatibility with auto-callouts, we allow a callout to be specified before a condition that is an assertion. First, check for the syntax of a callout; if found, adjust the temporary pointer that is used to check for an assertion condition. That's all that is needed! */ if (ptr[1] == CHAR_QUESTION_MARK && ptr[2] == CHAR_C) { for (i = 3;; i++) if (!IS_DIGIT(ptr[i])) break; if (ptr[i] == CHAR_RIGHT_PARENTHESIS) tempptr += i + 1; /* tempptr should now be pointing to the opening parenthesis of the assertion condition. */ if (*tempptr != CHAR_LEFT_PARENTHESIS) { *errorcodeptr = ERR28; goto FAILED; } } /* For conditions that are assertions, check the syntax, and then exit the switch. This will take control down to where bracketed groups, including assertions, are processed. */ if (tempptr[1] == CHAR_QUESTION_MARK && (tempptr[2] == CHAR_EQUALS_SIGN || tempptr[2] == CHAR_EXCLAMATION_MARK || (tempptr[2] == CHAR_LESS_THAN_SIGN && (tempptr[3] == CHAR_EQUALS_SIGN || tempptr[3] == CHAR_EXCLAMATION_MARK)))) { cd->iscondassert = TRUE; break; } /* Other conditions use OP_CREF/OP_DNCREF/OP_RREF/OP_DNRREF, and all need to skip at least 1+IMM2_SIZE bytes at the start of the group. */ code[1+LINK_SIZE] = OP_CREF; skipbytes = 1+IMM2_SIZE; refsign = -1; /* => not a number */ namelen = -1; /* => not a name; must set to avoid warning */ name = NULL; /* Always set to avoid warning */ recno = 0; /* Always set to avoid warning */ /* Check for a test for recursion in a named group. */ ptr++; if (*ptr == CHAR_R && ptr[1] == CHAR_AMPERSAND) { terminator = -1; ptr += 2; code[1+LINK_SIZE] = OP_RREF; /* Change the type of test */ } /* Check for a test for a named group's having been set, using the Perl syntax (?(<name>) or (?('name'), and also allow for the original PCRE syntax of (?(name) or for (?(+n), (?(-n), and just (?(n). */ else if (*ptr == CHAR_LESS_THAN_SIGN) { terminator = CHAR_GREATER_THAN_SIGN; ptr++; } else if (*ptr == CHAR_APOSTROPHE) { terminator = CHAR_APOSTROPHE; ptr++; } else { terminator = CHAR_NULL; if (*ptr == CHAR_MINUS || *ptr == CHAR_PLUS) refsign = *ptr++; else if (IS_DIGIT(*ptr)) refsign = 0; } /* Handle a number */ if (refsign >= 0) { while (IS_DIGIT(*ptr)) { if (recno > INT_MAX / 10 - 1) /* Integer overflow */ { while (IS_DIGIT(*ptr)) ptr++; *errorcodeptr = ERR61; goto FAILED; } recno = recno * 10 + (int)(*ptr - CHAR_0); ptr++; } } /* Otherwise we expect to read a name; anything else is an error. When a name is one of a number of duplicates, a different opcode is used and it needs more memory. Unfortunately we cannot tell whether a name is a duplicate in the first pass, so we have to allow for more memory. */ else { if (IS_DIGIT(*ptr)) { *errorcodeptr = ERR84; goto FAILED; } if (!MAX_255(*ptr) || (cd->ctypes[*ptr] & ctype_word) == 0) { *errorcodeptr = ERR28; /* Assertion expected */ goto FAILED; } name = ptr++; while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) { ptr++; } namelen = (int)(ptr - name); if (lengthptr != NULL) skipbytes += IMM2_SIZE; } /* Check the terminator */ if ((terminator > 0 && *ptr++ != (pcre_uchar)terminator) || *ptr++ != CHAR_RIGHT_PARENTHESIS) { ptr--; /* Error offset */ *errorcodeptr = ERR26; /* Malformed number or name */ goto FAILED; } /* Do no further checking in the pre-compile phase. */ if (lengthptr != NULL) break; /* In the real compile we do the work of looking for the actual reference. If refsign is not negative, it means we have a number in recno. */ if (refsign >= 0) { if (recno <= 0) { *errorcodeptr = ERR35; goto FAILED; } if (refsign != 0) recno = (refsign == CHAR_MINUS)? cd->bracount - recno + 1 : recno + cd->bracount; if (recno <= 0 || recno > cd->final_bracount) { *errorcodeptr = ERR15; goto FAILED; } PUT2(code, 2+LINK_SIZE, recno); if (recno > cd->top_backref) cd->top_backref = recno; break; } /* Otherwise look for the name. */ slot = cd->name_table; for (i = 0; i < cd->names_found; i++) { if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0 && slot[IMM2_SIZE+namelen] == 0) break; slot += cd->name_entry_size; } /* Found the named subpattern. If the name is duplicated, add one to the opcode to change CREF/RREF into DNCREF/DNRREF and insert appropriate data values. Otherwise, just insert the unique subpattern number. */ if (i < cd->names_found) { int offset = i++; int count = 1; recno = GET2(slot, 0); /* Number from first found */ if (recno > cd->top_backref) cd->top_backref = recno; for (; i < cd->names_found; i++) { slot += cd->name_entry_size; if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) != 0 || (slot+IMM2_SIZE)[namelen] != 0) break; count++; } if (count > 1) { PUT2(code, 2+LINK_SIZE, offset); PUT2(code, 2+LINK_SIZE+IMM2_SIZE, count); skipbytes += IMM2_SIZE; code[1+LINK_SIZE]++; } else /* Not a duplicated name */ { PUT2(code, 2+LINK_SIZE, recno); } } /* If terminator == CHAR_NULL it means that the name followed directly after the opening parenthesis [e.g. (?(abc)...] and in this case there are some further alternatives to try. For the cases where terminator != CHAR_NULL [things like (?(<name>... or (?('name')... or (?(R&name)... ] we have now checked all the possibilities, so give an error. */ else if (terminator != CHAR_NULL) { *errorcodeptr = ERR15; goto FAILED; } /* Check for (?(R) for recursion. Allow digits after R to specify a specific group number. */ else if (*name == CHAR_R) { recno = 0; for (i = 1; i < namelen; i++) { if (!IS_DIGIT(name[i])) { *errorcodeptr = ERR15; goto FAILED; } if (recno > INT_MAX / 10 - 1) /* Integer overflow */ { *errorcodeptr = ERR61; goto FAILED; } recno = recno * 10 + name[i] - CHAR_0; } if (recno == 0) recno = RREF_ANY; code[1+LINK_SIZE] = OP_RREF; /* Change test type */ PUT2(code, 2+LINK_SIZE, recno); } /* Similarly, check for the (?(DEFINE) "condition", which is always false. */ else if (namelen == 6 && STRNCMP_UC_C8(name, STRING_DEFINE, 6) == 0) { code[1+LINK_SIZE] = OP_DEF; skipbytes = 1; } /* Reference to an unidentified subpattern. */ else { *errorcodeptr = ERR15; goto FAILED; } break; /* ------------------------------------------------------------ */ case CHAR_EQUALS_SIGN: /* Positive lookahead */ bravalue = OP_ASSERT; cd->assert_depth += 1; ptr++; break; /* Optimize (?!) to (*FAIL) unless it is quantified - which is a weird thing to do, but Perl allows all assertions to be quantified, and when they contain capturing parentheses there may be a potential use for this feature. Not that that applies to a quantified (?!) but we allow it for uniformity. */ /* ------------------------------------------------------------ */ case CHAR_EXCLAMATION_MARK: /* Negative lookahead */ ptr++; if (*ptr == CHAR_RIGHT_PARENTHESIS && ptr[1] != CHAR_ASTERISK && ptr[1] != CHAR_PLUS && ptr[1] != CHAR_QUESTION_MARK && (ptr[1] != CHAR_LEFT_CURLY_BRACKET || !is_counted_repeat(ptr+2))) { *code++ = OP_FAIL; previous = NULL; continue; } bravalue = OP_ASSERT_NOT; cd->assert_depth += 1; break; /* ------------------------------------------------------------ */ case CHAR_LESS_THAN_SIGN: /* Lookbehind or named define */ switch (ptr[1]) { case CHAR_EQUALS_SIGN: /* Positive lookbehind */ bravalue = OP_ASSERTBACK; cd->assert_depth += 1; ptr += 2; break; case CHAR_EXCLAMATION_MARK: /* Negative lookbehind */ bravalue = OP_ASSERTBACK_NOT; cd->assert_depth += 1; ptr += 2; break; default: /* Could be name define, else bad */ if (MAX_255(ptr[1]) && (cd->ctypes[ptr[1]] & ctype_word) != 0) goto DEFINE_NAME; ptr++; /* Correct offset for error */ *errorcodeptr = ERR24; goto FAILED; } break; /* ------------------------------------------------------------ */ case CHAR_GREATER_THAN_SIGN: /* One-time brackets */ bravalue = OP_ONCE; ptr++; break; /* ------------------------------------------------------------ */ case CHAR_C: /* Callout - may be followed by digits; */ previous_callout = code; /* Save for later completion */ after_manual_callout = 1; /* Skip one item before completing */ *code++ = OP_CALLOUT; { int n = 0; ptr++; while(IS_DIGIT(*ptr)) { n = n * 10 + *ptr++ - CHAR_0; if (n > 255) { *errorcodeptr = ERR38; goto FAILED; } } if (*ptr != CHAR_RIGHT_PARENTHESIS) { *errorcodeptr = ERR39; goto FAILED; } *code++ = n; PUT(code, 0, (int)(ptr - cd->start_pattern + 1)); /* Pattern offset */ PUT(code, LINK_SIZE, 0); /* Default length */ code += 2 * LINK_SIZE; } previous = NULL; continue; /* ------------------------------------------------------------ */ case CHAR_P: /* Python-style named subpattern handling */ if (*(++ptr) == CHAR_EQUALS_SIGN || *ptr == CHAR_GREATER_THAN_SIGN) /* Reference or recursion */ { is_recurse = *ptr == CHAR_GREATER_THAN_SIGN; terminator = CHAR_RIGHT_PARENTHESIS; goto NAMED_REF_OR_RECURSE; } else if (*ptr != CHAR_LESS_THAN_SIGN) /* Test for Python-style defn */ { *errorcodeptr = ERR41; goto FAILED; } /* Fall through to handle (?P< as (?< is handled */ /* ------------------------------------------------------------ */ DEFINE_NAME: /* Come here from (?< handling */ case CHAR_APOSTROPHE: terminator = (*ptr == CHAR_LESS_THAN_SIGN)? CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE; name = ++ptr; if (IS_DIGIT(*ptr)) { *errorcodeptr = ERR84; /* Group name must start with non-digit */ goto FAILED; } while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++; namelen = (int)(ptr - name); /* In the pre-compile phase, do a syntax check, remember the longest name, and then remember the group in a vector, expanding it if necessary. Duplicates for the same number are skipped; other duplicates are checked for validity. In the actual compile, there is nothing to do. */ if (lengthptr != NULL) { named_group *ng; pcre_uint32 number = cd->bracount + 1; if (*ptr != (pcre_uchar)terminator) { *errorcodeptr = ERR42; goto FAILED; } if (cd->names_found >= MAX_NAME_COUNT) { *errorcodeptr = ERR49; goto FAILED; } if (namelen + IMM2_SIZE + 1 > cd->name_entry_size) { cd->name_entry_size = namelen + IMM2_SIZE + 1; if (namelen > MAX_NAME_SIZE) { *errorcodeptr = ERR48; goto FAILED; } } /* Scan the list to check for duplicates. For duplicate names, if the number is the same, break the loop, which causes the name to be discarded; otherwise, if DUPNAMES is not set, give an error. If it is set, allow the name with a different number, but continue scanning in case this is a duplicate with the same number. For non-duplicate names, give an error if the number is duplicated. */ ng = cd->named_groups; for (i = 0; i < cd->names_found; i++, ng++) { if (namelen == ng->length && STRNCMP_UC_UC(name, ng->name, namelen) == 0) { if (ng->number == number) break; if ((options & PCRE_DUPNAMES) == 0) { *errorcodeptr = ERR43; goto FAILED; } cd->dupnames = TRUE; /* Duplicate names exist */ } else if (ng->number == number) { *errorcodeptr = ERR65; goto FAILED; } } if (i >= cd->names_found) /* Not a duplicate with same number */ { /* Increase the list size if necessary */ if (cd->names_found >= cd->named_group_list_size) { int newsize = cd->named_group_list_size * 2; named_group *newspace = (PUBL(malloc)) (newsize * sizeof(named_group)); if (newspace == NULL) { *errorcodeptr = ERR21; goto FAILED; } memcpy(newspace, cd->named_groups, cd->named_group_list_size * sizeof(named_group)); if (cd->named_group_list_size > NAMED_GROUP_LIST_SIZE) (PUBL(free))((void *)cd->named_groups); cd->named_groups = newspace; cd->named_group_list_size = newsize; } cd->named_groups[cd->names_found].name = name; cd->named_groups[cd->names_found].length = namelen; cd->named_groups[cd->names_found].number = number; cd->names_found++; } } ptr++; /* Move past > or ' in both passes. */ goto NUMBERED_GROUP; /* ------------------------------------------------------------ */ case CHAR_AMPERSAND: /* Perl recursion/subroutine syntax */ terminator = CHAR_RIGHT_PARENTHESIS; is_recurse = TRUE; /* Fall through */ /* We come here from the Python syntax above that handles both references (?P=name) and recursion (?P>name), as well as falling through from the Perl recursion syntax (?&name). We also come here from the Perl \k<name> or \k'name' back reference syntax and the \k{name} .NET syntax, and the Oniguruma \g<...> and \g'...' subroutine syntax. */ NAMED_REF_OR_RECURSE: name = ++ptr; if (IS_DIGIT(*ptr)) { *errorcodeptr = ERR84; /* Group name must start with non-digit */ goto FAILED; } while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++; namelen = (int)(ptr - name); /* In the pre-compile phase, do a syntax check. We used to just set a dummy reference number, because it was not used in the first pass. However, with the change of recursive back references to be atomic, we have to look for the number so that this state can be identified, as otherwise the incorrect length is computed. If it's not a backwards reference, the dummy number will do. */ if (lengthptr != NULL) { named_group *ng; recno = 0; if (namelen == 0) { *errorcodeptr = ERR62; goto FAILED; } if (*ptr != (pcre_uchar)terminator) { *errorcodeptr = ERR42; goto FAILED; } if (namelen > MAX_NAME_SIZE) { *errorcodeptr = ERR48; goto FAILED; } /* Count named back references. */ if (!is_recurse) cd->namedrefcount++; /* We have to allow for a named reference to a duplicated name (this cannot be determined until the second pass). This needs an extra 16-bit data item. */ *lengthptr += IMM2_SIZE; /* If this is a forward reference and we are within a (?|...) group, the reference may end up as the number of a group which we are currently inside, that is, it could be a recursive reference. In the real compile this will be picked up and the reference wrapped with OP_ONCE to make it atomic, so we must space in case this occurs. */ /* In fact, this can happen for a non-forward reference because another group with the same number might be created later. This issue is fixed "properly" in PCRE2. As PCRE1 is now in maintenance only mode, we finesse the bug by allowing more memory always. */ *lengthptr += 4 + 4*LINK_SIZE; /* It is even worse than that. The current reference may be to an existing named group with a different number (so apparently not recursive) but which later on is also attached to a group with the current number. This can only happen if $(| has been previous encountered. In that case, we allow yet more memory, just in case. (Again, this is fixed "properly" in PCRE2. */ if (cd->dupgroups) *lengthptr += 4 + 4*LINK_SIZE; /* Otherwise, check for recursion here. The name table does not exist in the first pass; instead we must scan the list of names encountered so far in order to get the number. If the name is not found, leave the value of recno as 0 for a forward reference. */ /* This patch (removing "else") fixes a problem when a reference is to multiple identically named nested groups from within the nest. Once again, it is not the "proper" fix, and it results in an over-allocation of memory. */ /* else */ { ng = cd->named_groups; for (i = 0; i < cd->names_found; i++, ng++) { if (namelen == ng->length && STRNCMP_UC_UC(name, ng->name, namelen) == 0) { open_capitem *oc; recno = ng->number; if (is_recurse) break; for (oc = cd->open_caps; oc != NULL; oc = oc->next) { if (oc->number == recno) { oc->flag = TRUE; break; } } } } } } /* In the real compile, search the name table. We check the name first, and then check that we have reached the end of the name in the table. That way, if the name is longer than any in the table, the comparison will fail without reading beyond the table entry. */ else { slot = cd->name_table; for (i = 0; i < cd->names_found; i++) { if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0 && slot[IMM2_SIZE+namelen] == 0) break; slot += cd->name_entry_size; } if (i < cd->names_found) { recno = GET2(slot, 0); } else { *errorcodeptr = ERR15; goto FAILED; } } /* In both phases, for recursions, we can now go to the code than handles numerical recursion. */ if (is_recurse) goto HANDLE_RECURSION; /* In the second pass we must see if the name is duplicated. If so, we generate a different opcode. */ if (lengthptr == NULL && cd->dupnames) { int count = 1; unsigned int index = i; pcre_uchar *cslot = slot + cd->name_entry_size; for (i++; i < cd->names_found; i++) { if (STRCMP_UC_UC(slot + IMM2_SIZE, cslot + IMM2_SIZE) != 0) break; count++; cslot += cd->name_entry_size; } if (count > 1) { if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; *code++ = ((options & PCRE_CASELESS) != 0)? OP_DNREFI : OP_DNREF; PUT2INC(code, 0, index); PUT2INC(code, 0, count); /* Process each potentially referenced group. */ for (; slot < cslot; slot += cd->name_entry_size) { open_capitem *oc; recno = GET2(slot, 0); cd->backref_map |= (recno < 32)? (1U << recno) : 1; if (recno > cd->top_backref) cd->top_backref = recno; /* Check to see if this back reference is recursive, that it, it is inside the group that it references. A flag is set so that the group can be made atomic. */ for (oc = cd->open_caps; oc != NULL; oc = oc->next) { if (oc->number == recno) { oc->flag = TRUE; break; } } } continue; /* End of back ref handling */ } } /* First pass, or a non-duplicated name. */ goto HANDLE_REFERENCE; /* ------------------------------------------------------------ */ case CHAR_R: /* Recursion, same as (?0) */ recno = 0; if (*(++ptr) != CHAR_RIGHT_PARENTHESIS) { *errorcodeptr = ERR29; goto FAILED; } goto HANDLE_RECURSION; /* ------------------------------------------------------------ */ case CHAR_MINUS: case CHAR_PLUS: /* Recursion or subroutine */ case CHAR_0: case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: case CHAR_5: case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9: { const pcre_uchar *called; terminator = CHAR_RIGHT_PARENTHESIS; /* Come here from the \g<...> and \g'...' code (Oniguruma compatibility). However, the syntax has been checked to ensure that the ... are a (signed) number, so that neither ERR63 nor ERR29 will be called on this path, nor with the jump to OTHER_CHAR_AFTER_QUERY ever be taken. */ HANDLE_NUMERICAL_RECURSION: if ((refsign = *ptr) == CHAR_PLUS) { ptr++; if (!IS_DIGIT(*ptr)) { *errorcodeptr = ERR63; goto FAILED; } } else if (refsign == CHAR_MINUS) { if (!IS_DIGIT(ptr[1])) goto OTHER_CHAR_AFTER_QUERY; ptr++; } recno = 0; while(IS_DIGIT(*ptr)) { if (recno > INT_MAX / 10 - 1) /* Integer overflow */ { while (IS_DIGIT(*ptr)) ptr++; *errorcodeptr = ERR61; goto FAILED; } recno = recno * 10 + *ptr++ - CHAR_0; } if (*ptr != (pcre_uchar)terminator) { *errorcodeptr = ERR29; goto FAILED; } if (refsign == CHAR_MINUS) { if (recno == 0) { *errorcodeptr = ERR58; goto FAILED; } recno = cd->bracount - recno + 1; if (recno <= 0) { *errorcodeptr = ERR15; goto FAILED; } } else if (refsign == CHAR_PLUS) { if (recno == 0) { *errorcodeptr = ERR58; goto FAILED; } recno += cd->bracount; } /* Come here from code above that handles a named recursion */ HANDLE_RECURSION: previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; called = cd->start_code; /* When we are actually compiling, find the bracket that is being referenced. Temporarily end the regex in case it doesn't exist before this point. If we end up with a forward reference, first check that the bracket does occur later so we can give the error (and position) now. Then remember this forward reference in the workspace so it can be filled in at the end. */ if (lengthptr == NULL) { *code = OP_END; if (recno != 0) called = PRIV(find_bracket)(cd->start_code, utf, recno); /* Forward reference */ if (called == NULL) { if (recno > cd->final_bracount) { *errorcodeptr = ERR15; goto FAILED; } /* Fudge the value of "called" so that when it is inserted as an offset below, what it actually inserted is the reference number of the group. Then remember the forward reference. */ called = cd->start_code + recno; if (cd->hwm >= cd->start_workspace + cd->workspace_size - WORK_SIZE_SAFETY_MARGIN) { *errorcodeptr = expand_workspace(cd); if (*errorcodeptr != 0) goto FAILED; } PUTINC(cd->hwm, 0, (int)(code + 1 - cd->start_code)); } /* If not a forward reference, and the subpattern is still open, this is a recursive call. We check to see if this is a left recursion that could loop for ever, and diagnose that case. We must not, however, do this check if we are in a conditional subpattern because the condition might be testing for recursion in a pattern such as /(?(R)a+|(?R)b)/, which is perfectly valid. Forever loops are also detected at runtime, so those that occur in conditional subpatterns will be picked up then. */ else if (GET(called, 1) == 0 && cond_depth <= 0 && could_be_empty(called, code, bcptr, utf, cd)) { *errorcodeptr = ERR40; goto FAILED; } } /* Insert the recursion/subroutine item. It does not have a set first character (relevant if it is repeated, because it will then be wrapped with ONCE brackets). */ *code = OP_RECURSE; PUT(code, 1, (int)(called - cd->start_code)); code += 1 + LINK_SIZE; groupsetfirstchar = FALSE; } /* Can't determine a first byte now */ if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; continue; /* ------------------------------------------------------------ */ default: /* Other characters: check option setting */ OTHER_CHAR_AFTER_QUERY: set = unset = 0; optset = &set; while (*ptr != CHAR_RIGHT_PARENTHESIS && *ptr != CHAR_COLON) { switch (*ptr++) { case CHAR_MINUS: optset = &unset; break; case CHAR_J: /* Record that it changed in the external options */ *optset |= PCRE_DUPNAMES; cd->external_flags |= PCRE_JCHANGED; break; case CHAR_i: *optset |= PCRE_CASELESS; break; case CHAR_m: *optset |= PCRE_MULTILINE; break; case CHAR_s: *optset |= PCRE_DOTALL; break; case CHAR_x: *optset |= PCRE_EXTENDED; break; case CHAR_U: *optset |= PCRE_UNGREEDY; break; case CHAR_X: *optset |= PCRE_EXTRA; break; default: *errorcodeptr = ERR12; ptr--; /* Correct the offset */ goto FAILED; } } /* Set up the changed option bits, but don't change anything yet. */ newoptions = (options | set) & (~unset); /* If the options ended with ')' this is not the start of a nested group with option changes, so the options change at this level. If we are not at the pattern start, reset the greedy defaults and the case value for firstchar and reqchar. */ if (*ptr == CHAR_RIGHT_PARENTHESIS) { greedy_default = ((newoptions & PCRE_UNGREEDY) != 0); greedy_non_default = greedy_default ^ 1; req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS:0; /* Change options at this level, and pass them back for use in subsequent branches. */ *optionsptr = options = newoptions; previous = NULL; /* This item can't be repeated */ continue; /* It is complete */ } /* If the options ended with ':' we are heading into a nested group with possible change of options. Such groups are non-capturing and are not assertions of any kind. All we need to do is skip over the ':'; the newoptions value is handled below. */ bravalue = OP_BRA; ptr++; } /* End of switch for character following (? */ } /* End of (? handling */ /* Opening parenthesis not followed by '*' or '?'. If PCRE_NO_AUTO_CAPTURE is set, all unadorned brackets become non-capturing and behave like (?:...) brackets. */ else if ((options & PCRE_NO_AUTO_CAPTURE) != 0) { bravalue = OP_BRA; } /* Else we have a capturing group. */ else { NUMBERED_GROUP: cd->bracount += 1; PUT2(code, 1+LINK_SIZE, cd->bracount); skipbytes = IMM2_SIZE; } /* Process nested bracketed regex. First check for parentheses nested too deeply. */ if ((cd->parens_depth += 1) > PARENS_NEST_LIMIT) { *errorcodeptr = ERR82; goto FAILED; } /* All assertions used not to be repeatable, but this was changed for Perl compatibility. All kinds can now be repeated except for assertions that are conditions (Perl also forbids these to be repeated). We copy code into a non-register variable (tempcode) in order to be able to pass its address because some compilers complain otherwise. At the start of a conditional group whose condition is an assertion, cd->iscondassert is set. We unset it here so as to allow assertions later in the group to be quantified. */ if (bravalue >= OP_ASSERT && bravalue <= OP_ASSERTBACK_NOT && cd->iscondassert) { previous = NULL; cd->iscondassert = FALSE; } else { previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; } *code = bravalue; tempcode = code; tempreqvary = cd->req_varyopt; /* Save value before bracket */ tempbracount = cd->bracount; /* Save value before bracket */ length_prevgroup = 0; /* Initialize for pre-compile phase */ if (!compile_regex( newoptions, /* The complete new option state */ &tempcode, /* Where to put code (updated) */ &ptr, /* Input pointer (updated) */ errorcodeptr, /* Where to put an error message */ (bravalue == OP_ASSERTBACK || bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */ reset_bracount, /* True if (?| group */ skipbytes, /* Skip over bracket number */ cond_depth + ((bravalue == OP_COND)?1:0), /* Depth of condition subpatterns */ &subfirstchar, /* For possible first char */ &subfirstcharflags, &subreqchar, /* For possible last char */ &subreqcharflags, bcptr, /* Current branch chain */ cd, /* Tables block */ (lengthptr == NULL)? NULL : /* Actual compile phase */ &length_prevgroup /* Pre-compile phase */ )) goto FAILED; cd->parens_depth -= 1; /* If this was an atomic group and there are no capturing groups within it, generate OP_ONCE_NC instead of OP_ONCE. */ if (bravalue == OP_ONCE && cd->bracount <= tempbracount) *code = OP_ONCE_NC; if (bravalue >= OP_ASSERT && bravalue <= OP_ASSERTBACK_NOT) cd->assert_depth -= 1; /* At the end of compiling, code is still pointing to the start of the group, while tempcode has been updated to point past the end of the group. The pattern pointer (ptr) is on the bracket. If this is a conditional bracket, check that there are no more than two branches in the group, or just one if it's a DEFINE group. We do this in the real compile phase, not in the pre-pass, where the whole group may not be available. */ if (bravalue == OP_COND && lengthptr == NULL) { pcre_uchar *tc = code; int condcount = 0; do { condcount++; tc += GET(tc,1); } while (*tc != OP_KET); /* A DEFINE group is never obeyed inline (the "condition" is always false). It must have only one branch. */ if (code[LINK_SIZE+1] == OP_DEF) { if (condcount > 1) { *errorcodeptr = ERR54; goto FAILED; } bravalue = OP_DEF; /* Just a flag to suppress char handling below */ } /* A "normal" conditional group. If there is just one branch, we must not make use of its firstchar or reqchar, because this is equivalent to an empty second branch. */ else { if (condcount > 2) { *errorcodeptr = ERR27; goto FAILED; } if (condcount == 1) subfirstcharflags = subreqcharflags = REQ_NONE; } } /* Error if hit end of pattern */ if (*ptr != CHAR_RIGHT_PARENTHESIS) { *errorcodeptr = ERR14; goto FAILED; } /* In the pre-compile phase, update the length by the length of the group, less the brackets at either end. Then reduce the compiled code to just a set of non-capturing brackets so that it doesn't use much memory if it is duplicated by a quantifier.*/ if (lengthptr != NULL) { if (OFLOW_MAX - *lengthptr < length_prevgroup - 2 - 2*LINK_SIZE) { *errorcodeptr = ERR20; goto FAILED; } *lengthptr += length_prevgroup - 2 - 2*LINK_SIZE; code++; /* This already contains bravalue */ PUTINC(code, 0, 1 + LINK_SIZE); *code++ = OP_KET; PUTINC(code, 0, 1 + LINK_SIZE); break; /* No need to waste time with special character handling */ } /* Otherwise update the main code pointer to the end of the group. */ code = tempcode; /* For a DEFINE group, required and first character settings are not relevant. */ if (bravalue == OP_DEF) break; /* Handle updating of the required and first characters for other types of group. Update for normal brackets of all kinds, and conditions with two branches (see code above). If the bracket is followed by a quantifier with zero repeat, we have to back off. Hence the definition of zeroreqchar and zerofirstchar outside the main loop so that they can be accessed for the back off. */ zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; groupsetfirstchar = FALSE; if (bravalue >= OP_ONCE) { /* If we have not yet set a firstchar in this branch, take it from the subpattern, remembering that it was set here so that a repeat of more than one can replicate it as reqchar if necessary. If the subpattern has no firstchar, set "none" for the whole branch. In both cases, a zero repeat forces firstchar to "none". */ if (firstcharflags == REQ_UNSET) { if (subfirstcharflags >= 0) { firstchar = subfirstchar; firstcharflags = subfirstcharflags; groupsetfirstchar = TRUE; } else firstcharflags = REQ_NONE; zerofirstcharflags = REQ_NONE; } /* If firstchar was previously set, convert the subpattern's firstchar into reqchar if there wasn't one, using the vary flag that was in existence beforehand. */ else if (subfirstcharflags >= 0 && subreqcharflags < 0) { subreqchar = subfirstchar; subreqcharflags = subfirstcharflags | tempreqvary; } /* If the subpattern set a required byte (or set a first byte that isn't really the first byte - see above), set it. */ if (subreqcharflags >= 0) { reqchar = subreqchar; reqcharflags = subreqcharflags; } } /* For a forward assertion, we take the reqchar, if set, provided that the group has also set a first char. This can be helpful if the pattern that follows the assertion doesn't set a different char. For example, it's useful for /(?=abcde).+/. We can't set firstchar for an assertion, however because it leads to incorrect effect for patterns such as /(?=a)a.+/ when the "real" "a" would then become a reqchar instead of a firstchar. This is overcome by a scan at the end if there's no firstchar, looking for an asserted first char. */ else if (bravalue == OP_ASSERT && subreqcharflags >= 0 && subfirstcharflags >= 0) { reqchar = subreqchar; reqcharflags = subreqcharflags; } break; /* End of processing '(' */ /* ===================================================================*/ /* Handle metasequences introduced by \. For ones like \d, the ESC_ values are arranged to be the negation of the corresponding OP_values in the default case when PCRE_UCP is not set. For the back references, the values are negative the reference number. Only back references and those types that consume a character may be repeated. We can test for values between ESC_b and ESC_Z for the latter; this may have to change if any new ones are ever created. */ case CHAR_BACKSLASH: tempptr = ptr; escape = check_escape(&ptr, &ec, errorcodeptr, cd->bracount, options, FALSE); if (*errorcodeptr != 0) goto FAILED; if (escape == 0) /* The escape coded a single character */ c = ec; else { /* For metasequences that actually match a character, we disable the setting of a first character if it hasn't already been set. */ if (firstcharflags == REQ_UNSET && escape > ESC_b && escape < ESC_Z) firstcharflags = REQ_NONE; /* Set values to reset to if this is followed by a zero repeat. */ zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; /* \g<name> or \g'name' is a subroutine call by name and \g<n> or \g'n' is a subroutine call by number (Oniguruma syntax). In fact, the value ESC_g is returned only for these cases. So we don't need to check for < or ' if the value is ESC_g. For the Perl syntax \g{n} the value is -n, and for the Perl syntax \g{name} the result is ESC_k (as that is a synonym for a named back reference). */ if (escape == ESC_g) { const pcre_uchar *p; pcre_uint32 cf; item_hwm_offset = cd->hwm - cd->start_workspace; /* Normally this is set when '(' is read */ terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)? CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE; /* These two statements stop the compiler for warning about possibly unset variables caused by the jump to HANDLE_NUMERICAL_RECURSION. In fact, because we do the check for a number below, the paths that would actually be in error are never taken. */ skipbytes = 0; reset_bracount = FALSE; /* If it's not a signed or unsigned number, treat it as a name. */ cf = ptr[1]; if (cf != CHAR_PLUS && cf != CHAR_MINUS && !IS_DIGIT(cf)) { is_recurse = TRUE; goto NAMED_REF_OR_RECURSE; } /* Signed or unsigned number (cf = ptr[1]) is known to be plus or minus or a digit. */ p = ptr + 2; while (IS_DIGIT(*p)) p++; if (*p != (pcre_uchar)terminator) { *errorcodeptr = ERR57; goto FAILED; } ptr++; goto HANDLE_NUMERICAL_RECURSION; } /* \k<name> or \k'name' is a back reference by name (Perl syntax). We also support \k{name} (.NET syntax). */ if (escape == ESC_k) { if ((ptr[1] != CHAR_LESS_THAN_SIGN && ptr[1] != CHAR_APOSTROPHE && ptr[1] != CHAR_LEFT_CURLY_BRACKET)) { *errorcodeptr = ERR69; goto FAILED; } is_recurse = FALSE; terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)? CHAR_GREATER_THAN_SIGN : (*ptr == CHAR_APOSTROPHE)? CHAR_APOSTROPHE : CHAR_RIGHT_CURLY_BRACKET; goto NAMED_REF_OR_RECURSE; } /* Back references are handled specially; must disable firstchar if not set to cope with cases like (?=(\w+))\1: which would otherwise set ':' later. */ if (escape < 0) { open_capitem *oc; recno = -escape; /* Come here from named backref handling when the reference is to a single group (i.e. not to a duplicated name. */ HANDLE_REFERENCE: if (firstcharflags == REQ_UNSET) zerofirstcharflags = firstcharflags = REQ_NONE; previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; *code++ = ((options & PCRE_CASELESS) != 0)? OP_REFI : OP_REF; PUT2INC(code, 0, recno); cd->backref_map |= (recno < 32)? (1U << recno) : 1; if (recno > cd->top_backref) cd->top_backref = recno; /* Check to see if this back reference is recursive, that it, it is inside the group that it references. A flag is set so that the group can be made atomic. */ for (oc = cd->open_caps; oc != NULL; oc = oc->next) { if (oc->number == recno) { oc->flag = TRUE; break; } } } /* So are Unicode property matches, if supported. */ #ifdef SUPPORT_UCP else if (escape == ESC_P || escape == ESC_p) { BOOL negated; unsigned int ptype = 0, pdata = 0; if (!get_ucp(&ptr, &negated, &ptype, &pdata, errorcodeptr)) goto FAILED; previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; *code++ = ((escape == ESC_p) != negated)? OP_PROP : OP_NOTPROP; *code++ = ptype; *code++ = pdata; } #else /* If Unicode properties are not supported, \X, \P, and \p are not allowed. */ else if (escape == ESC_X || escape == ESC_P || escape == ESC_p) { *errorcodeptr = ERR45; goto FAILED; } #endif /* For the rest (including \X when Unicode properties are supported), we can obtain the OP value by negating the escape value in the default situation when PCRE_UCP is not set. When it *is* set, we substitute Unicode property tests. Note that \b and \B do a one-character lookbehind, and \A also behaves as if it does. */ else { if ((escape == ESC_b || escape == ESC_B || escape == ESC_A) && cd->max_lookbehind == 0) cd->max_lookbehind = 1; #ifdef SUPPORT_UCP if (escape >= ESC_DU && escape <= ESC_wu) { nestptr = ptr + 1; /* Where to resume */ ptr = substitutes[escape - ESC_DU] - 1; /* Just before substitute */ } else #endif /* In non-UTF-8 mode, we turn \C into OP_ALLANY instead of OP_ANYBYTE so that it works in DFA mode and in lookbehinds. */ { previous = (escape > ESC_b && escape < ESC_Z)? code : NULL; item_hwm_offset = cd->hwm - cd->start_workspace; *code++ = (!utf && escape == ESC_C)? OP_ALLANY : escape; } } continue; } /* We have a data character whose value is in c. In UTF-8 mode it may have a value > 127. We set its representation in the length/buffer, and then handle it as a data character. */ #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) mclength = PRIV(ord2utf)(c, mcbuffer); else #endif { mcbuffer[0] = c; mclength = 1; } goto ONE_CHAR; /* ===================================================================*/ /* Handle a literal character. It is guaranteed not to be whitespace or # when the extended flag is set. If we are in a UTF mode, it may be a multi-unit literal character. */ default: NORMAL_CHAR: mclength = 1; mcbuffer[0] = c; #ifdef SUPPORT_UTF if (utf && HAS_EXTRALEN(c)) ACROSSCHAR(TRUE, ptr[1], mcbuffer[mclength++] = *(++ptr)); #endif /* At this point we have the character's bytes in mcbuffer, and the length in mclength. When not in UTF-8 mode, the length is always 1. */ ONE_CHAR: previous = code; item_hwm_offset = cd->hwm - cd->start_workspace; /* For caseless UTF-8 mode when UCP support is available, check whether this character has more than one other case. If so, generate a special OP_PROP item instead of OP_CHARI. */ #ifdef SUPPORT_UCP if (utf && (options & PCRE_CASELESS) != 0) { GETCHAR(c, mcbuffer); if ((c = UCD_CASESET(c)) != 0) { *code++ = OP_PROP; *code++ = PT_CLIST; *code++ = c; if (firstcharflags == REQ_UNSET) firstcharflags = zerofirstcharflags = REQ_NONE; break; } } #endif /* Caseful matches, or not one of the multicase characters. */ *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARI : OP_CHAR; for (c = 0; c < mclength; c++) *code++ = mcbuffer[c]; /* Remember if \r or \n were seen */ if (mcbuffer[0] == CHAR_CR || mcbuffer[0] == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; /* Set the first and required bytes appropriately. If no previous first byte, set it from this character, but revert to none on a zero repeat. Otherwise, leave the firstchar value alone, and don't change it on a zero repeat. */ if (firstcharflags == REQ_UNSET) { zerofirstcharflags = REQ_NONE; zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; /* If the character is more than one byte long, we can set firstchar only if it is not to be matched caselessly. */ if (mclength == 1 || req_caseopt == 0) { firstchar = mcbuffer[0]; firstcharflags = req_caseopt; if (mclength != 1) { reqchar = code[-1]; reqcharflags = cd->req_varyopt; } } else firstcharflags = reqcharflags = REQ_NONE; } /* firstchar was previously set; we can set reqchar only if the length is 1 or the matching is caseful. */ else { zerofirstchar = firstchar; zerofirstcharflags = firstcharflags; zeroreqchar = reqchar; zeroreqcharflags = reqcharflags; if (mclength == 1 || req_caseopt == 0) { reqchar = code[-1]; reqcharflags = req_caseopt | cd->req_varyopt; } } break; /* End of literal character handling */ } } /* end of big loop */ /* Control never reaches here by falling through, only by a goto for all the error states. Pass back the position in the pattern so that it can be displayed to the user for diagnosing the error. */ FAILED: *ptrptr = ptr; return FALSE; } /************************************************* * Compile sequence of alternatives * *************************************************/ /* On entry, ptr is pointing past the bracket character, but on return it points to the closing bracket, or vertical bar, or end of string. The code variable is pointing at the byte into which the BRA operator has been stored. This function is used during the pre-compile phase when we are trying to find out the amount of memory needed, as well as during the real compile phase. The value of lengthptr distinguishes the two phases. Arguments: options option bits, including any changes for this subpattern codeptr -> the address of the current code pointer ptrptr -> the address of the current pattern pointer errorcodeptr -> pointer to error code variable lookbehind TRUE if this is a lookbehind assertion reset_bracount TRUE to reset the count for each branch skipbytes skip this many bytes at start (for brackets and OP_COND) cond_depth depth of nesting for conditional subpatterns firstcharptr place to put the first required character firstcharflagsptr place to put the first character flags, or a negative number reqcharptr place to put the last required character reqcharflagsptr place to put the last required character flags, or a negative number bcptr pointer to the chain of currently open branches cd points to the data block with tables pointers etc. lengthptr NULL during the real compile phase points to length accumulator during pre-compile phase Returns: TRUE on success */ static BOOL compile_regex(int options, pcre_uchar **codeptr, const pcre_uchar **ptrptr, int *errorcodeptr, BOOL lookbehind, BOOL reset_bracount, int skipbytes, int cond_depth, pcre_uint32 *firstcharptr, pcre_int32 *firstcharflagsptr, pcre_uint32 *reqcharptr, pcre_int32 *reqcharflagsptr, branch_chain *bcptr, compile_data *cd, int *lengthptr) { const pcre_uchar *ptr = *ptrptr; pcre_uchar *code = *codeptr; pcre_uchar *last_branch = code; pcre_uchar *start_bracket = code; pcre_uchar *reverse_count = NULL; open_capitem capitem; int capnumber = 0; pcre_uint32 firstchar, reqchar; pcre_int32 firstcharflags, reqcharflags; pcre_uint32 branchfirstchar, branchreqchar; pcre_int32 branchfirstcharflags, branchreqcharflags; int length; unsigned int orig_bracount; unsigned int max_bracount; branch_chain bc; size_t save_hwm_offset; /* If set, call the external function that checks for stack availability. */ if (PUBL(stack_guard) != NULL && PUBL(stack_guard)()) { *errorcodeptr= ERR85; return FALSE; } /* Miscellaneous initialization */ bc.outer = bcptr; bc.current_branch = code; firstchar = reqchar = 0; firstcharflags = reqcharflags = REQ_UNSET; save_hwm_offset = cd->hwm - cd->start_workspace; /* Accumulate the length for use in the pre-compile phase. Start with the length of the BRA and KET and any extra bytes that are required at the beginning. We accumulate in a local variable to save frequent testing of lenthptr for NULL. We cannot do this by looking at the value of code at the start and end of each alternative, because compiled items are discarded during the pre-compile phase so that the work space is not exceeded. */ length = 2 + 2*LINK_SIZE + skipbytes; /* WARNING: If the above line is changed for any reason, you must also change the code that abstracts option settings at the start of the pattern and makes them global. It tests the value of length for (2 + 2*LINK_SIZE) in the pre-compile phase to find out whether anything has yet been compiled or not. */ /* If this is a capturing subpattern, add to the chain of open capturing items so that we can detect them if (*ACCEPT) is encountered. This is also used to detect groups that contain recursive back references to themselves. Note that only OP_CBRA need be tested here; changing this opcode to one of its variants, e.g. OP_SCBRAPOS, happens later, after the group has been compiled. */ if (*code == OP_CBRA) { capnumber = GET2(code, 1 + LINK_SIZE); capitem.number = capnumber; capitem.next = cd->open_caps; capitem.flag = FALSE; cd->open_caps = &capitem; } /* Offset is set zero to mark that this bracket is still open */ PUT(code, 1, 0); code += 1 + LINK_SIZE + skipbytes; /* Loop for each alternative branch */ orig_bracount = max_bracount = cd->bracount; for (;;) { /* For a (?| group, reset the capturing bracket count so that each branch uses the same numbers. */ if (reset_bracount) cd->bracount = orig_bracount; /* Set up dummy OP_REVERSE if lookbehind assertion */ if (lookbehind) { *code++ = OP_REVERSE; reverse_count = code; PUTINC(code, 0, 0); length += 1 + LINK_SIZE; } /* Now compile the branch; in the pre-compile phase its length gets added into the length. */ if (!compile_branch(&options, &code, &ptr, errorcodeptr, &branchfirstchar, &branchfirstcharflags, &branchreqchar, &branchreqcharflags, &bc, cond_depth, cd, (lengthptr == NULL)? NULL : &length)) { *ptrptr = ptr; return FALSE; } /* Keep the highest bracket count in case (?| was used and some branch has fewer than the rest. */ if (cd->bracount > max_bracount) max_bracount = cd->bracount; /* In the real compile phase, there is some post-processing to be done. */ if (lengthptr == NULL) { /* If this is the first branch, the firstchar and reqchar values for the branch become the values for the regex. */ if (*last_branch != OP_ALT) { firstchar = branchfirstchar; firstcharflags = branchfirstcharflags; reqchar = branchreqchar; reqcharflags = branchreqcharflags; } /* If this is not the first branch, the first char and reqchar have to match the values from all the previous branches, except that if the previous value for reqchar didn't have REQ_VARY set, it can still match, and we set REQ_VARY for the regex. */ else { /* If we previously had a firstchar, but it doesn't match the new branch, we have to abandon the firstchar for the regex, but if there was previously no reqchar, it takes on the value of the old firstchar. */ if (firstcharflags >= 0 && (firstcharflags != branchfirstcharflags || firstchar != branchfirstchar)) { if (reqcharflags < 0) { reqchar = firstchar; reqcharflags = firstcharflags; } firstcharflags = REQ_NONE; } /* If we (now or from before) have no firstchar, a firstchar from the branch becomes a reqchar if there isn't a branch reqchar. */ if (firstcharflags < 0 && branchfirstcharflags >= 0 && branchreqcharflags < 0) { branchreqchar = branchfirstchar; branchreqcharflags = branchfirstcharflags; } /* Now ensure that the reqchars match */ if (((reqcharflags & ~REQ_VARY) != (branchreqcharflags & ~REQ_VARY)) || reqchar != branchreqchar) reqcharflags = REQ_NONE; else { reqchar = branchreqchar; reqcharflags |= branchreqcharflags; /* To "or" REQ_VARY */ } } /* If lookbehind, check that this branch matches a fixed-length string, and put the length into the OP_REVERSE item. Temporarily mark the end of the branch with OP_END. If the branch contains OP_RECURSE, the result is -3 because there may be forward references that we can't check here. Set a flag to cause another lookbehind check at the end. Why not do it all at the end? Because common, erroneous checks are picked up here and the offset of the problem can be shown. */ if (lookbehind) { int fixed_length; *code = OP_END; fixed_length = find_fixedlength(last_branch, (options & PCRE_UTF8) != 0, FALSE, cd, NULL); DPRINTF(("fixed length = %d\n", fixed_length)); if (fixed_length == -3) { cd->check_lookbehind = TRUE; } else if (fixed_length < 0) { *errorcodeptr = (fixed_length == -2)? ERR36 : (fixed_length == -4)? ERR70: ERR25; *ptrptr = ptr; return FALSE; } else { if (fixed_length > cd->max_lookbehind) cd->max_lookbehind = fixed_length; PUT(reverse_count, 0, fixed_length); } } } /* Reached end of expression, either ')' or end of pattern. In the real compile phase, go back through the alternative branches and reverse the chain of offsets, with the field in the BRA item now becoming an offset to the first alternative. If there are no alternatives, it points to the end of the group. The length in the terminating ket is always the length of the whole bracketed item. Return leaving the pointer at the terminating char. */ if (*ptr != CHAR_VERTICAL_LINE) { if (lengthptr == NULL) { int branch_length = (int)(code - last_branch); do { int prev_length = GET(last_branch, 1); PUT(last_branch, 1, branch_length); branch_length = prev_length; last_branch -= branch_length; } while (branch_length > 0); } /* Fill in the ket */ *code = OP_KET; PUT(code, 1, (int)(code - start_bracket)); code += 1 + LINK_SIZE; /* If it was a capturing subpattern, check to see if it contained any recursive back references. If so, we must wrap it in atomic brackets. Because we are moving code along, we must ensure that any pending recursive references are updated. In any event, remove the block from the chain. */ if (capnumber > 0) { if (cd->open_caps->flag) { *code = OP_END; adjust_recurse(start_bracket, 1 + LINK_SIZE, (options & PCRE_UTF8) != 0, cd, save_hwm_offset); memmove(start_bracket + 1 + LINK_SIZE, start_bracket, IN_UCHARS(code - start_bracket)); *start_bracket = OP_ONCE; code += 1 + LINK_SIZE; PUT(start_bracket, 1, (int)(code - start_bracket)); *code = OP_KET; PUT(code, 1, (int)(code - start_bracket)); code += 1 + LINK_SIZE; length += 2 + 2*LINK_SIZE; } cd->open_caps = cd->open_caps->next; } /* Retain the highest bracket number, in case resetting was used. */ cd->bracount = max_bracount; /* Set values to pass back */ *codeptr = code; *ptrptr = ptr; *firstcharptr = firstchar; *firstcharflagsptr = firstcharflags; *reqcharptr = reqchar; *reqcharflagsptr = reqcharflags; if (lengthptr != NULL) { if (OFLOW_MAX - *lengthptr < length) { *errorcodeptr = ERR20; return FALSE; } *lengthptr += length; } return TRUE; } /* Another branch follows. In the pre-compile phase, we can move the code pointer back to where it was for the start of the first branch. (That is, pretend that each branch is the only one.) In the real compile phase, insert an ALT node. Its length field points back to the previous branch while the bracket remains open. At the end the chain is reversed. It's done like this so that the start of the bracket has a zero offset until it is closed, making it possible to detect recursion. */ if (lengthptr != NULL) { code = *codeptr + 1 + LINK_SIZE + skipbytes; length += 1 + LINK_SIZE; } else { *code = OP_ALT; PUT(code, 1, (int)(code - last_branch)); bc.current_branch = last_branch = code; code += 1 + LINK_SIZE; } ptr++; } /* Control never reaches here */ } /************************************************* * Check for anchored expression * *************************************************/ /* Try to find out if this is an anchored regular expression. Consider each alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then it's anchored. However, if this is a multiline pattern, then only OP_SOD will be found, because ^ generates OP_CIRCM in that mode. We can also consider a regex to be anchored if OP_SOM starts all its branches. This is the code for \G, which means "match at start of match position, taking into account the match offset". A branch is also implicitly anchored if it starts with .* and DOTALL is set, because that will try the rest of the pattern at all possible matching points, so there is no point trying again.... er .... .... except when the .* appears inside capturing parentheses, and there is a subsequent back reference to those parentheses. We haven't enough information to catch that case precisely. At first, the best we could do was to detect when .* was in capturing brackets and the highest back reference was greater than or equal to that level. However, by keeping a bitmap of the first 31 back references, we can catch some of the more common cases more precisely. ... A second exception is when the .* appears inside an atomic group, because this prevents the number of characters it matches from being adjusted. Arguments: code points to start of expression (the bracket) bracket_map a bitmap of which brackets we are inside while testing; this handles up to substring 31; after that we just have to take the less precise approach cd points to the compile data block atomcount atomic group level Returns: TRUE or FALSE */ static BOOL is_anchored(register const pcre_uchar *code, unsigned int bracket_map, compile_data *cd, int atomcount) { do { const pcre_uchar *scode = first_significant_code( code + PRIV(OP_lengths)[*code], FALSE); register int op = *scode; /* Non-capturing brackets */ if (op == OP_BRA || op == OP_BRAPOS || op == OP_SBRA || op == OP_SBRAPOS) { if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; } /* Capturing brackets */ else if (op == OP_CBRA || op == OP_CBRAPOS || op == OP_SCBRA || op == OP_SCBRAPOS) { int n = GET2(scode, 1+LINK_SIZE); int new_map = bracket_map | ((n < 32)? (1U << n) : 1); if (!is_anchored(scode, new_map, cd, atomcount)) return FALSE; } /* Positive forward assertion */ else if (op == OP_ASSERT) { if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; } /* Condition; not anchored if no second branch */ else if (op == OP_COND) { if (scode[GET(scode,1)] != OP_ALT) return FALSE; if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; } /* Atomic groups */ else if (op == OP_ONCE || op == OP_ONCE_NC) { if (!is_anchored(scode, bracket_map, cd, atomcount + 1)) return FALSE; } /* .* is not anchored unless DOTALL is set (which generates OP_ALLANY) and it isn't in brackets that are or may be referenced or inside an atomic group. */ else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR || op == OP_TYPEPOSSTAR)) { if (scode[1] != OP_ALLANY || (bracket_map & cd->backref_map) != 0 || atomcount > 0 || cd->had_pruneorskip) return FALSE; } /* Check for explicit anchoring */ else if (op != OP_SOD && op != OP_SOM && op != OP_CIRC) return FALSE; code += GET(code, 1); } while (*code == OP_ALT); /* Loop for each alternative */ return TRUE; } /************************************************* * Check for starting with ^ or .* * *************************************************/ /* This is called to find out if every branch starts with ^ or .* so that "first char" processing can be done to speed things up in multiline matching and for non-DOTALL patterns that start with .* (which must start at the beginning or after \n). As in the case of is_anchored() (see above), we have to take account of back references to capturing brackets that contain .* because in that case we can't make the assumption. Also, the appearance of .* inside atomic brackets or in an assertion, or in a pattern that contains *PRUNE or *SKIP does not count, because once again the assumption no longer holds. Arguments: code points to start of expression (the bracket) bracket_map a bitmap of which brackets we are inside while testing; this handles up to substring 31; after that we just have to take the less precise approach cd points to the compile data atomcount atomic group level inassert TRUE if in an assertion Returns: TRUE or FALSE */ static BOOL is_startline(const pcre_uchar *code, unsigned int bracket_map, compile_data *cd, int atomcount, BOOL inassert) { do { const pcre_uchar *scode = first_significant_code( code + PRIV(OP_lengths)[*code], FALSE); register int op = *scode; /* If we are at the start of a conditional assertion group, *both* the conditional assertion *and* what follows the condition must satisfy the test for start of line. Other kinds of condition fail. Note that there may be an auto-callout at the start of a condition. */ if (op == OP_COND) { scode += 1 + LINK_SIZE; if (*scode == OP_CALLOUT) scode += PRIV(OP_lengths)[OP_CALLOUT]; switch (*scode) { case OP_CREF: case OP_DNCREF: case OP_RREF: case OP_DNRREF: case OP_DEF: case OP_FAIL: return FALSE; default: /* Assertion */ if (!is_startline(scode, bracket_map, cd, atomcount, TRUE)) return FALSE; do scode += GET(scode, 1); while (*scode == OP_ALT); scode += 1 + LINK_SIZE; break; } scode = first_significant_code(scode, FALSE); op = *scode; } /* Non-capturing brackets */ if (op == OP_BRA || op == OP_BRAPOS || op == OP_SBRA || op == OP_SBRAPOS) { if (!is_startline(scode, bracket_map, cd, atomcount, inassert)) return FALSE; } /* Capturing brackets */ else if (op == OP_CBRA || op == OP_CBRAPOS || op == OP_SCBRA || op == OP_SCBRAPOS) { int n = GET2(scode, 1+LINK_SIZE); int new_map = bracket_map | ((n < 32)? (1U << n) : 1); if (!is_startline(scode, new_map, cd, atomcount, inassert)) return FALSE; } /* Positive forward assertions */ else if (op == OP_ASSERT) { if (!is_startline(scode, bracket_map, cd, atomcount, TRUE)) return FALSE; } /* Atomic brackets */ else if (op == OP_ONCE || op == OP_ONCE_NC) { if (!is_startline(scode, bracket_map, cd, atomcount + 1, inassert)) return FALSE; } /* .* means "start at start or after \n" if it isn't in atomic brackets or brackets that may be referenced or an assertion, as long as the pattern does not contain *PRUNE or *SKIP, because these break the feature. Consider, for example, /.*?a(*PRUNE)b/ with the subject "aab", which matches "ab", i.e. not at the start of a line. */ else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR || op == OP_TYPEPOSSTAR) { if (scode[1] != OP_ANY || (bracket_map & cd->backref_map) != 0 || atomcount > 0 || cd->had_pruneorskip || inassert) return FALSE; } /* Check for explicit circumflex; anything else gives a FALSE result. Note in particular that this includes atomic brackets OP_ONCE and OP_ONCE_NC because the number of characters matched by .* cannot be adjusted inside them. */ else if (op != OP_CIRC && op != OP_CIRCM) return FALSE; /* Move on to the next alternative */ code += GET(code, 1); } while (*code == OP_ALT); /* Loop for each alternative */ return TRUE; } /************************************************* * Check for asserted fixed first char * *************************************************/ /* During compilation, the "first char" settings from forward assertions are discarded, because they can cause conflicts with actual literals that follow. However, if we end up without a first char setting for an unanchored pattern, it is worth scanning the regex to see if there is an initial asserted first char. If all branches start with the same asserted char, or with a non-conditional bracket all of whose alternatives start with the same asserted char (recurse ad lib), then we return that char, with the flags set to zero or REQ_CASELESS; otherwise return zero with REQ_NONE in the flags. Arguments: code points to start of expression (the bracket) flags points to the first char flags, or to REQ_NONE inassert TRUE if in an assertion Returns: the fixed first char, or 0 with REQ_NONE in flags */ static pcre_uint32 find_firstassertedchar(const pcre_uchar *code, pcre_int32 *flags, BOOL inassert) { register pcre_uint32 c = 0; int cflags = REQ_NONE; *flags = REQ_NONE; do { pcre_uint32 d; int dflags; int xl = (*code == OP_CBRA || *code == OP_SCBRA || *code == OP_CBRAPOS || *code == OP_SCBRAPOS)? IMM2_SIZE:0; const pcre_uchar *scode = first_significant_code(code + 1+LINK_SIZE + xl, TRUE); register pcre_uchar op = *scode; switch(op) { default: return 0; case OP_BRA: case OP_BRAPOS: case OP_CBRA: case OP_SCBRA: case OP_CBRAPOS: case OP_SCBRAPOS: case OP_ASSERT: case OP_ONCE: case OP_ONCE_NC: d = find_firstassertedchar(scode, &dflags, op == OP_ASSERT); if (dflags < 0) return 0; if (cflags < 0) { c = d; cflags = dflags; } else if (c != d || cflags != dflags) return 0; break; case OP_EXACT: scode += IMM2_SIZE; /* Fall through */ case OP_CHAR: case OP_PLUS: case OP_MINPLUS: case OP_POSPLUS: if (!inassert) return 0; if (cflags < 0) { c = scode[1]; cflags = 0; } else if (c != scode[1]) return 0; break; case OP_EXACTI: scode += IMM2_SIZE; /* Fall through */ case OP_CHARI: case OP_PLUSI: case OP_MINPLUSI: case OP_POSPLUSI: if (!inassert) return 0; if (cflags < 0) { c = scode[1]; cflags = REQ_CASELESS; } else if (c != scode[1]) return 0; break; } code += GET(code, 1); } while (*code == OP_ALT); *flags = cflags; return c; } /************************************************* * Add an entry to the name/number table * *************************************************/ /* This function is called between compiling passes to add an entry to the name/number table, maintaining alphabetical order. Checking for permitted and forbidden duplicates has already been done. Arguments: cd the compile data block name the name to add length the length of the name groupno the group number Returns: nothing */ static void add_name(compile_data *cd, const pcre_uchar *name, int length, unsigned int groupno) { int i; pcre_uchar *slot = cd->name_table; for (i = 0; i < cd->names_found; i++) { int crc = memcmp(name, slot+IMM2_SIZE, IN_UCHARS(length)); if (crc == 0 && slot[IMM2_SIZE+length] != 0) crc = -1; /* Current name is a substring */ /* Make space in the table and break the loop for an earlier name. For a duplicate or later name, carry on. We do this for duplicates so that in the simple case (when ?(| is not used) they are in order of their numbers. In all cases they are in the order in which they appear in the pattern. */ if (crc < 0) { memmove(slot + cd->name_entry_size, slot, IN_UCHARS((cd->names_found - i) * cd->name_entry_size)); break; } /* Continue the loop for a later or duplicate name */ slot += cd->name_entry_size; } PUT2(slot, 0, groupno); memcpy(slot + IMM2_SIZE, name, IN_UCHARS(length)); slot[IMM2_SIZE + length] = 0; cd->names_found++; } /************************************************* * Compile a Regular Expression * *************************************************/ /* This function takes a string and returns a pointer to a block of store holding a compiled version of the expression. The original API for this function had no error code return variable; it is retained for backwards compatibility. The new function is given a new name. Arguments: pattern the regular expression options various option bits errorcodeptr pointer to error code variable (pcre_compile2() only) can be NULL if you don't want a code value errorptr pointer to pointer to error text erroroffset ptr offset in pattern where error was detected tables pointer to character tables or NULL Returns: pointer to compiled data block, or NULL on error, with errorptr and erroroffset set */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION pcre_compile(const char *pattern, int options, const char **errorptr, int *erroroffset, const unsigned char *tables) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION pcre16_compile(PCRE_SPTR16 pattern, int options, const char **errorptr, int *erroroffset, const unsigned char *tables) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN pcre32 * PCRE_CALL_CONVENTION pcre32_compile(PCRE_SPTR32 pattern, int options, const char **errorptr, int *erroroffset, const unsigned char *tables) #endif { #if defined COMPILE_PCRE8 return pcre_compile2(pattern, options, NULL, errorptr, erroroffset, tables); #elif defined COMPILE_PCRE16 return pcre16_compile2(pattern, options, NULL, errorptr, erroroffset, tables); #elif defined COMPILE_PCRE32 return pcre32_compile2(pattern, options, NULL, errorptr, erroroffset, tables); #endif } #if defined COMPILE_PCRE8 PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION pcre_compile2(const char *pattern, int options, int *errorcodeptr, const char **errorptr, int *erroroffset, const unsigned char *tables) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION pcre16_compile2(PCRE_SPTR16 pattern, int options, int *errorcodeptr, const char **errorptr, int *erroroffset, const unsigned char *tables) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN pcre32 * PCRE_CALL_CONVENTION pcre32_compile2(PCRE_SPTR32 pattern, int options, int *errorcodeptr, const char **errorptr, int *erroroffset, const unsigned char *tables) #endif { REAL_PCRE *re; int length = 1; /* For final END opcode */ pcre_int32 firstcharflags, reqcharflags; pcre_uint32 firstchar, reqchar; pcre_uint32 limit_match = PCRE_UINT32_MAX; pcre_uint32 limit_recursion = PCRE_UINT32_MAX; int newline; int errorcode = 0; int skipatstart = 0; BOOL utf; BOOL never_utf = FALSE; size_t size; pcre_uchar *code; const pcre_uchar *codestart; const pcre_uchar *ptr; compile_data compile_block; compile_data *cd = &compile_block; /* This space is used for "compiling" into during the first phase, when we are computing the amount of memory that is needed. Compiled items are thrown away as soon as possible, so that a fairly large buffer should be sufficient for this purpose. The same space is used in the second phase for remembering where to fill in forward references to subpatterns. That may overflow, in which case new memory is obtained from malloc(). */ pcre_uchar cworkspace[COMPILE_WORK_SIZE]; /* This vector is used for remembering name groups during the pre-compile. In a similar way to cworkspace, it can be expanded using malloc() if necessary. */ named_group named_groups[NAMED_GROUP_LIST_SIZE]; /* Set this early so that early errors get offset 0. */ ptr = (const pcre_uchar *)pattern; /* We can't pass back an error message if errorptr is NULL; I guess the best we can do is just return NULL, but we can set a code value if there is a code pointer. */ if (errorptr == NULL) { if (errorcodeptr != NULL) *errorcodeptr = 99; return NULL; } *errorptr = NULL; if (errorcodeptr != NULL) *errorcodeptr = ERR0; /* However, we can give a message for this error */ if (erroroffset == NULL) { errorcode = ERR16; goto PCRE_EARLY_ERROR_RETURN2; } *erroroffset = 0; /* Set up pointers to the individual character tables */ if (tables == NULL) tables = PRIV(default_tables); cd->lcc = tables + lcc_offset; cd->fcc = tables + fcc_offset; cd->cbits = tables + cbits_offset; cd->ctypes = tables + ctypes_offset; /* Check that all undefined public option bits are zero */ if ((options & ~PUBLIC_COMPILE_OPTIONS) != 0) { errorcode = ERR17; goto PCRE_EARLY_ERROR_RETURN; } /* If PCRE_NEVER_UTF is set, remember it. */ if ((options & PCRE_NEVER_UTF) != 0) never_utf = TRUE; /* Check for global one-time settings at the start of the pattern, and remember the offset for later. */ cd->external_flags = 0; /* Initialize here for LIMIT_MATCH/RECURSION */ while (ptr[skipatstart] == CHAR_LEFT_PARENTHESIS && ptr[skipatstart+1] == CHAR_ASTERISK) { int newnl = 0; int newbsr = 0; /* For completeness and backward compatibility, (*UTFn) is supported in the relevant libraries, but (*UTF) is generic and always supported. Note that PCRE_UTF8 == PCRE_UTF16 == PCRE_UTF32. */ #ifdef COMPILE_PCRE8 if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF8_RIGHTPAR, 5) == 0) { skipatstart += 7; options |= PCRE_UTF8; continue; } #endif #ifdef COMPILE_PCRE16 if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF16_RIGHTPAR, 6) == 0) { skipatstart += 8; options |= PCRE_UTF16; continue; } #endif #ifdef COMPILE_PCRE32 if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF32_RIGHTPAR, 6) == 0) { skipatstart += 8; options |= PCRE_UTF32; continue; } #endif else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF_RIGHTPAR, 4) == 0) { skipatstart += 6; options |= PCRE_UTF8; continue; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UCP_RIGHTPAR, 4) == 0) { skipatstart += 6; options |= PCRE_UCP; continue; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_AUTO_POSSESS_RIGHTPAR, 16) == 0) { skipatstart += 18; options |= PCRE_NO_AUTO_POSSESS; continue; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_START_OPT_RIGHTPAR, 13) == 0) { skipatstart += 15; options |= PCRE_NO_START_OPTIMIZE; continue; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LIMIT_MATCH_EQ, 12) == 0) { pcre_uint32 c = 0; int p = skipatstart + 14; while (isdigit(ptr[p])) { if (c > PCRE_UINT32_MAX / 10 - 1) break; /* Integer overflow */ c = c*10 + ptr[p++] - CHAR_0; } if (ptr[p++] != CHAR_RIGHT_PARENTHESIS) break; if (c < limit_match) { limit_match = c; cd->external_flags |= PCRE_MLSET; } skipatstart = p; continue; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LIMIT_RECURSION_EQ, 16) == 0) { pcre_uint32 c = 0; int p = skipatstart + 18; while (isdigit(ptr[p])) { if (c > PCRE_UINT32_MAX / 10 - 1) break; /* Integer overflow check */ c = c*10 + ptr[p++] - CHAR_0; } if (ptr[p++] != CHAR_RIGHT_PARENTHESIS) break; if (c < limit_recursion) { limit_recursion = c; cd->external_flags |= PCRE_RLSET; } skipatstart = p; continue; } if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CR_RIGHTPAR, 3) == 0) { skipatstart += 5; newnl = PCRE_NEWLINE_CR; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LF_RIGHTPAR, 3) == 0) { skipatstart += 5; newnl = PCRE_NEWLINE_LF; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CRLF_RIGHTPAR, 5) == 0) { skipatstart += 7; newnl = PCRE_NEWLINE_CR + PCRE_NEWLINE_LF; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANY_RIGHTPAR, 4) == 0) { skipatstart += 6; newnl = PCRE_NEWLINE_ANY; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANYCRLF_RIGHTPAR, 8) == 0) { skipatstart += 10; newnl = PCRE_NEWLINE_ANYCRLF; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_ANYCRLF_RIGHTPAR, 12) == 0) { skipatstart += 14; newbsr = PCRE_BSR_ANYCRLF; } else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_UNICODE_RIGHTPAR, 12) == 0) { skipatstart += 14; newbsr = PCRE_BSR_UNICODE; } if (newnl != 0) options = (options & ~PCRE_NEWLINE_BITS) | newnl; else if (newbsr != 0) options = (options & ~(PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) | newbsr; else break; } /* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */ utf = (options & PCRE_UTF8) != 0; if (utf && never_utf) { errorcode = ERR78; goto PCRE_EARLY_ERROR_RETURN2; } /* Can't support UTF unless PCRE has been compiled to include the code. The return of an error code from PRIV(valid_utf)() is a new feature, introduced in release 8.13. It is passed back from pcre_[dfa_]exec(), but at the moment is not used here. */ #ifdef SUPPORT_UTF if (utf && (options & PCRE_NO_UTF8_CHECK) == 0 && (errorcode = PRIV(valid_utf)((PCRE_PUCHAR)pattern, -1, erroroffset)) != 0) { #if defined COMPILE_PCRE8 errorcode = ERR44; #elif defined COMPILE_PCRE16 errorcode = ERR74; #elif defined COMPILE_PCRE32 errorcode = ERR77; #endif goto PCRE_EARLY_ERROR_RETURN2; } #else if (utf) { errorcode = ERR32; goto PCRE_EARLY_ERROR_RETURN; } #endif /* Can't support UCP unless PCRE has been compiled to include the code. */ #ifndef SUPPORT_UCP if ((options & PCRE_UCP) != 0) { errorcode = ERR67; goto PCRE_EARLY_ERROR_RETURN; } #endif /* Check validity of \R options. */ if ((options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) == (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) { errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN; } /* Handle different types of newline. The three bits give seven cases. The current code allows for fixed one- or two-byte sequences, plus "any" and "anycrlf". */ switch (options & PCRE_NEWLINE_BITS) { case 0: newline = NEWLINE; break; /* Build-time default */ case PCRE_NEWLINE_CR: newline = CHAR_CR; break; case PCRE_NEWLINE_LF: newline = CHAR_NL; break; case PCRE_NEWLINE_CR+ PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; case PCRE_NEWLINE_ANY: newline = -1; break; case PCRE_NEWLINE_ANYCRLF: newline = -2; break; default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN; } if (newline == -2) { cd->nltype = NLTYPE_ANYCRLF; } else if (newline < 0) { cd->nltype = NLTYPE_ANY; } else { cd->nltype = NLTYPE_FIXED; if (newline > 255) { cd->nllen = 2; cd->nl[0] = (newline >> 8) & 255; cd->nl[1] = newline & 255; } else { cd->nllen = 1; cd->nl[0] = newline; } } /* Maximum back reference and backref bitmap. The bitmap records up to 31 back references to help in deciding whether (.*) can be treated as anchored or not. */ cd->top_backref = 0; cd->backref_map = 0; /* Reflect pattern for debugging output */ DPRINTF(("------------------------------------------------------------------\n")); #ifdef PCRE_DEBUG print_puchar(stdout, (PCRE_PUCHAR)pattern); #endif DPRINTF(("\n")); /* Pretend to compile the pattern while actually just accumulating the length of memory required. This behaviour is triggered by passing a non-NULL final argument to compile_regex(). We pass a block of workspace (cworkspace) for it to compile parts of the pattern into; the compiled code is discarded when it is no longer needed, so hopefully this workspace will never overflow, though there is a test for its doing so. */ cd->bracount = cd->final_bracount = 0; cd->names_found = 0; cd->name_entry_size = 0; cd->name_table = NULL; cd->dupnames = FALSE; cd->dupgroups = FALSE; cd->namedrefcount = 0; cd->start_code = cworkspace; cd->hwm = cworkspace; cd->iscondassert = FALSE; cd->start_workspace = cworkspace; cd->workspace_size = COMPILE_WORK_SIZE; cd->named_groups = named_groups; cd->named_group_list_size = NAMED_GROUP_LIST_SIZE; cd->start_pattern = (const pcre_uchar *)pattern; cd->end_pattern = (const pcre_uchar *)(pattern + STRLEN_UC((const pcre_uchar *)pattern)); cd->req_varyopt = 0; cd->parens_depth = 0; cd->assert_depth = 0; cd->max_lookbehind = 0; cd->external_options = options; cd->open_caps = NULL; /* Now do the pre-compile. On error, errorcode will be set non-zero, so we don't need to look at the result of the function here. The initial options have been put into the cd block so that they can be changed if an option setting is found within the regex right at the beginning. Bringing initial option settings outside can help speed up starting point checks. */ ptr += skipatstart; code = cworkspace; *code = OP_BRA; (void)compile_regex(cd->external_options, &code, &ptr, &errorcode, FALSE, FALSE, 0, 0, &firstchar, &firstcharflags, &reqchar, &reqcharflags, NULL, cd, &length); if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN; DPRINTF(("end pre-compile: length=%d workspace=%d\n", length, (int)(cd->hwm - cworkspace))); if (length > MAX_PATTERN_SIZE) { errorcode = ERR20; goto PCRE_EARLY_ERROR_RETURN; } /* Compute the size of the data block for storing the compiled pattern. Integer overflow should no longer be possible because nowadays we limit the maximum value of cd->names_found and cd->name_entry_size. */ size = sizeof(REAL_PCRE) + (length + cd->names_found * cd->name_entry_size) * sizeof(pcre_uchar); /* Get the memory. */ re = (REAL_PCRE *)(PUBL(malloc))(size); if (re == NULL) { errorcode = ERR21; goto PCRE_EARLY_ERROR_RETURN; } /* Put in the magic number, and save the sizes, initial options, internal flags, and character table pointer. NULL is used for the default character tables. The nullpad field is at the end; it's there to help in the case when a regex compiled on a system with 4-byte pointers is run on another with 8-byte pointers. */ re->magic_number = MAGIC_NUMBER; re->size = (int)size; re->options = cd->external_options; re->flags = cd->external_flags; re->limit_match = limit_match; re->limit_recursion = limit_recursion; re->first_char = 0; re->req_char = 0; re->name_table_offset = sizeof(REAL_PCRE) / sizeof(pcre_uchar); re->name_entry_size = cd->name_entry_size; re->name_count = cd->names_found; re->ref_count = 0; re->tables = (tables == PRIV(default_tables))? NULL : tables; re->nullpad = NULL; #ifdef COMPILE_PCRE32 re->dummy = 0; #else re->dummy1 = re->dummy2 = re->dummy3 = 0; #endif /* The starting points of the name/number translation table and of the code are passed around in the compile data block. The start/end pattern and initial options are already set from the pre-compile phase, as is the name_entry_size field. Reset the bracket count and the names_found field. Also reset the hwm field; this time it's used for remembering forward references to subpatterns. */ cd->final_bracount = cd->bracount; /* Save for checking forward references */ cd->parens_depth = 0; cd->assert_depth = 0; cd->bracount = 0; cd->max_lookbehind = 0; cd->name_table = (pcre_uchar *)re + re->name_table_offset; codestart = cd->name_table + re->name_entry_size * re->name_count; cd->start_code = codestart; cd->hwm = (pcre_uchar *)(cd->start_workspace); cd->iscondassert = FALSE; cd->req_varyopt = 0; cd->had_accept = FALSE; cd->had_pruneorskip = FALSE; cd->check_lookbehind = FALSE; cd->open_caps = NULL; /* If any named groups were found, create the name/number table from the list created in the first pass. */ if (cd->names_found > 0) { int i = cd->names_found; named_group *ng = cd->named_groups; cd->names_found = 0; for (; i > 0; i--, ng++) add_name(cd, ng->name, ng->length, ng->number); if (cd->named_group_list_size > NAMED_GROUP_LIST_SIZE) (PUBL(free))((void *)cd->named_groups); } /* Set up a starting, non-extracting bracket, then compile the expression. On error, errorcode will be set non-zero, so we don't need to look at the result of the function here. */ ptr = (const pcre_uchar *)pattern + skipatstart; code = (pcre_uchar *)codestart; *code = OP_BRA; (void)compile_regex(re->options, &code, &ptr, &errorcode, FALSE, FALSE, 0, 0, &firstchar, &firstcharflags, &reqchar, &reqcharflags, NULL, cd, NULL); re->top_bracket = cd->bracount; re->top_backref = cd->top_backref; re->max_lookbehind = cd->max_lookbehind; re->flags = cd->external_flags | PCRE_MODE; if (cd->had_accept) { reqchar = 0; /* Must disable after (*ACCEPT) */ reqcharflags = REQ_NONE; } /* If not reached end of pattern on success, there's an excess bracket. */ if (errorcode == 0 && *ptr != CHAR_NULL) errorcode = ERR22; /* Fill in the terminating state and check for disastrous overflow, but if debugging, leave the test till after things are printed out. */ *code++ = OP_END; #ifndef PCRE_DEBUG if (code - codestart > length) errorcode = ERR23; #endif #ifdef SUPPORT_VALGRIND /* If the estimated length exceeds the really used length, mark the extra allocated memory as unaddressable, so that any out-of-bound reads can be detected. */ VALGRIND_MAKE_MEM_NOACCESS(code, (length - (code - codestart)) * sizeof(pcre_uchar)); #endif /* Fill in any forward references that are required. There may be repeated references; optimize for them, as searching a large regex takes time. */ if (cd->hwm > cd->start_workspace) { int prev_recno = -1; const pcre_uchar *groupptr = NULL; while (errorcode == 0 && cd->hwm > cd->start_workspace) { int offset, recno; cd->hwm -= LINK_SIZE; offset = GET(cd->hwm, 0); /* Check that the hwm handling hasn't gone wrong. This whole area is rewritten in PCRE2 because there are some obscure cases. */ if (offset == 0 || codestart[offset-1] != OP_RECURSE) { errorcode = ERR10; break; } recno = GET(codestart, offset); if (recno != prev_recno) { groupptr = PRIV(find_bracket)(codestart, utf, recno); prev_recno = recno; } if (groupptr == NULL) errorcode = ERR53; else PUT(((pcre_uchar *)codestart), offset, (int)(groupptr - codestart)); } } /* If the workspace had to be expanded, free the new memory. Set the pointer to NULL to indicate that forward references have been filled in. */ if (cd->workspace_size > COMPILE_WORK_SIZE) (PUBL(free))((void *)cd->start_workspace); cd->start_workspace = NULL; /* Give an error if there's back reference to a non-existent capturing subpattern. */ if (errorcode == 0 && re->top_backref > re->top_bracket) errorcode = ERR15; /* Unless disabled, check whether any single character iterators can be auto-possessified. The function overwrites the appropriate opcode values, so the type of the pointer must be cast. NOTE: the intermediate variable "temp" is used in this code because at least one compiler gives a warning about loss of "const" attribute if the cast (pcre_uchar *)codestart is used directly in the function call. */ if (errorcode == 0 && (options & PCRE_NO_AUTO_POSSESS) == 0) { pcre_uchar *temp = (pcre_uchar *)codestart; auto_possessify(temp, utf, cd); } /* If there were any lookbehind assertions that contained OP_RECURSE (recursions or subroutine calls), a flag is set for them to be checked here, because they may contain forward references. Actual recursions cannot be fixed length, but subroutine calls can. It is done like this so that those without OP_RECURSE that are not fixed length get a diagnosic with a useful offset. The exceptional ones forgo this. We scan the pattern to check that they are fixed length, and set their lengths. */ if (errorcode == 0 && cd->check_lookbehind) { pcre_uchar *cc = (pcre_uchar *)codestart; /* Loop, searching for OP_REVERSE items, and process those that do not have their length set. (Actually, it will also re-process any that have a length of zero, but that is a pathological case, and it does no harm.) When we find one, we temporarily terminate the branch it is in while we scan it. */ for (cc = (pcre_uchar *)PRIV(find_bracket)(codestart, utf, -1); cc != NULL; cc = (pcre_uchar *)PRIV(find_bracket)(cc, utf, -1)) { if (GET(cc, 1) == 0) { int fixed_length; pcre_uchar *be = cc - 1 - LINK_SIZE + GET(cc, -LINK_SIZE); int end_op = *be; *be = OP_END; fixed_length = find_fixedlength(cc, (re->options & PCRE_UTF8) != 0, TRUE, cd, NULL); *be = end_op; DPRINTF(("fixed length = %d\n", fixed_length)); if (fixed_length < 0) { errorcode = (fixed_length == -2)? ERR36 : (fixed_length == -4)? ERR70 : ERR25; break; } if (fixed_length > cd->max_lookbehind) cd->max_lookbehind = fixed_length; PUT(cc, 1, fixed_length); } cc += 1 + LINK_SIZE; } } /* Failed to compile, or error while post-processing */ if (errorcode != 0) { (PUBL(free))(re); PCRE_EARLY_ERROR_RETURN: *erroroffset = (int)(ptr - (const pcre_uchar *)pattern); PCRE_EARLY_ERROR_RETURN2: *errorptr = find_error_text(errorcode); if (errorcodeptr != NULL) *errorcodeptr = errorcode; return NULL; } /* If the anchored option was not passed, set the flag if we can determine that the pattern is anchored by virtue of ^ characters or \A or anything else, such as starting with non-atomic .* when DOTALL is set and there are no occurrences of *PRUNE or *SKIP. Otherwise, if we know what the first byte has to be, save it, because that speeds up unanchored matches no end. If not, see if we can set the PCRE_STARTLINE flag. This is helpful for multiline matches when all branches start with ^. and also when all branches start with non-atomic .* for non-DOTALL matches when *PRUNE and SKIP are not present. */ if ((re->options & PCRE_ANCHORED) == 0) { if (is_anchored(codestart, 0, cd, 0)) re->options |= PCRE_ANCHORED; else { if (firstcharflags < 0) firstchar = find_firstassertedchar(codestart, &firstcharflags, FALSE); if (firstcharflags >= 0) /* Remove caseless flag for non-caseable chars */ { #if defined COMPILE_PCRE8 re->first_char = firstchar & 0xff; #elif defined COMPILE_PCRE16 re->first_char = firstchar & 0xffff; #elif defined COMPILE_PCRE32 re->first_char = firstchar; #endif if ((firstcharflags & REQ_CASELESS) != 0) { #if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) /* We ignore non-ASCII first chars in 8 bit mode. */ if (utf) { if (re->first_char < 128) { if (cd->fcc[re->first_char] != re->first_char) re->flags |= PCRE_FCH_CASELESS; } else if (UCD_OTHERCASE(re->first_char) != re->first_char) re->flags |= PCRE_FCH_CASELESS; } else #endif if (MAX_255(re->first_char) && cd->fcc[re->first_char] != re->first_char) re->flags |= PCRE_FCH_CASELESS; } re->flags |= PCRE_FIRSTSET; } else if (is_startline(codestart, 0, cd, 0, FALSE)) re->flags |= PCRE_STARTLINE; } } /* For an anchored pattern, we use the "required byte" only if it follows a variable length item in the regex. Remove the caseless flag for non-caseable bytes. */ if (reqcharflags >= 0 && ((re->options & PCRE_ANCHORED) == 0 || (reqcharflags & REQ_VARY) != 0)) { #if defined COMPILE_PCRE8 re->req_char = reqchar & 0xff; #elif defined COMPILE_PCRE16 re->req_char = reqchar & 0xffff; #elif defined COMPILE_PCRE32 re->req_char = reqchar; #endif if ((reqcharflags & REQ_CASELESS) != 0) { #if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) /* We ignore non-ASCII first chars in 8 bit mode. */ if (utf) { if (re->req_char < 128) { if (cd->fcc[re->req_char] != re->req_char) re->flags |= PCRE_RCH_CASELESS; } else if (UCD_OTHERCASE(re->req_char) != re->req_char) re->flags |= PCRE_RCH_CASELESS; } else #endif if (MAX_255(re->req_char) && cd->fcc[re->req_char] != re->req_char) re->flags |= PCRE_RCH_CASELESS; } re->flags |= PCRE_REQCHSET; } /* Print out the compiled data if debugging is enabled. This is never the case when building a production library. */ #ifdef PCRE_DEBUG printf("Length = %d top_bracket = %d top_backref = %d\n", length, re->top_bracket, re->top_backref); printf("Options=%08x\n", re->options); if ((re->flags & PCRE_FIRSTSET) != 0) { pcre_uchar ch = re->first_char; const char *caseless = ((re->flags & PCRE_FCH_CASELESS) == 0)? "" : " (caseless)"; if (PRINTABLE(ch)) printf("First char = %c%s\n", ch, caseless); else printf("First char = \\x%02x%s\n", ch, caseless); } if ((re->flags & PCRE_REQCHSET) != 0) { pcre_uchar ch = re->req_char; const char *caseless = ((re->flags & PCRE_RCH_CASELESS) == 0)? "" : " (caseless)"; if (PRINTABLE(ch)) printf("Req char = %c%s\n", ch, caseless); else printf("Req char = \\x%02x%s\n", ch, caseless); } #if defined COMPILE_PCRE8 pcre_printint((pcre *)re, stdout, TRUE); #elif defined COMPILE_PCRE16 pcre16_printint((pcre *)re, stdout, TRUE); #elif defined COMPILE_PCRE32 pcre32_printint((pcre *)re, stdout, TRUE); #endif /* This check is done here in the debugging case so that the code that was compiled can be seen. */ if (code - codestart > length) { (PUBL(free))(re); *errorptr = find_error_text(ERR23); *erroroffset = ptr - (pcre_uchar *)pattern; if (errorcodeptr != NULL) *errorcodeptr = ERR23; return NULL; } #endif /* PCRE_DEBUG */ /* Check for a pattern than can match an empty string, so that this information can be provided to applications. */ do { if (could_be_empty_branch(codestart, code, utf, cd, NULL)) { re->flags |= PCRE_MATCH_EMPTY; break; } codestart += GET(codestart, 1); } while (*codestart == OP_ALT); #if defined COMPILE_PCRE8 return (pcre *)re; #elif defined COMPILE_PCRE16 return (pcre16 *)re; #elif defined COMPILE_PCRE32 return (pcre32 *)re; #endif } /* End of pcre_compile.c */
libgit2-main
deps/pcre/pcre_compile.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2013 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This module contains an internal function that is used to match an extended class. It is used by both pcre_exec() and pcre_def_exec(). */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre_internal.h" /************************************************* * Match character against an XCLASS * *************************************************/ /* This function is called to match a character against an extended class that might contain values > 255 and/or Unicode properties. Arguments: c the character data points to the flag byte of the XCLASS data Returns: TRUE if character matches, else FALSE */ BOOL PRIV(xclass)(pcre_uint32 c, const pcre_uchar *data, BOOL utf) { pcre_uchar t; BOOL negated = (*data & XCL_NOT) != 0; (void)utf; #ifdef COMPILE_PCRE8 /* In 8 bit mode, this must always be TRUE. Help the compiler to know that. */ utf = TRUE; #endif /* Character values < 256 are matched against a bitmap, if one is present. If not, we still carry on, because there may be ranges that start below 256 in the additional data. */ if (c < 256) { if ((*data & XCL_HASPROP) == 0) { if ((*data & XCL_MAP) == 0) return negated; return (((pcre_uint8 *)(data + 1))[c/8] & (1 << (c&7))) != 0; } if ((*data & XCL_MAP) != 0 && (((pcre_uint8 *)(data + 1))[c/8] & (1 << (c&7))) != 0) return !negated; /* char found */ } /* First skip the bit map if present. Then match against the list of Unicode properties or large chars or ranges that end with a large char. We won't ever encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */ if ((*data++ & XCL_MAP) != 0) data += 32 / sizeof(pcre_uchar); while ((t = *data++) != XCL_END) { pcre_uint32 x, y; if (t == XCL_SINGLE) { #ifdef SUPPORT_UTF if (utf) { GETCHARINC(x, data); /* macro generates multiple statements */ } else #endif x = *data++; if (c == x) return !negated; } else if (t == XCL_RANGE) { #ifdef SUPPORT_UTF if (utf) { GETCHARINC(x, data); /* macro generates multiple statements */ GETCHARINC(y, data); /* macro generates multiple statements */ } else #endif { x = *data++; y = *data++; } if (c >= x && c <= y) return !negated; } #ifdef SUPPORT_UCP else /* XCL_PROP & XCL_NOTPROP */ { const ucd_record *prop = GET_UCD(c); BOOL isprop = t == XCL_PROP; switch(*data) { case PT_ANY: if (isprop) return !negated; break; case PT_LAMP: if ((prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || prop->chartype == ucp_Lt) == isprop) return !negated; break; case PT_GC: if ((data[1] == PRIV(ucp_gentype)[prop->chartype]) == isprop) return !negated; break; case PT_PC: if ((data[1] == prop->chartype) == isprop) return !negated; break; case PT_SC: if ((data[1] == prop->script) == isprop) return !negated; break; case PT_ALNUM: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || PRIV(ucp_gentype)[prop->chartype] == ucp_N) == isprop) return !negated; break; /* Perl space used to exclude VT, but from Perl 5.18 it is included, which means that Perl space and POSIX space are now identical. PCRE was changed at release 8.34. */ case PT_SPACE: /* Perl space */ case PT_PXSPACE: /* POSIX space */ switch(c) { HSPACE_CASES: VSPACE_CASES: if (isprop) return !negated; break; default: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == isprop) return !negated; break; } break; case PT_WORD: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || PRIV(ucp_gentype)[prop->chartype] == ucp_N || c == CHAR_UNDERSCORE) == isprop) return !negated; break; case PT_UCNC: if (c < 0xa0) { if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || c == CHAR_GRAVE_ACCENT) == isprop) return !negated; } else { if ((c < 0xd800 || c > 0xdfff) == isprop) return !negated; } break; /* The following three properties can occur only in an XCLASS, as there is no \p or \P coding for them. */ /* Graphic character. Implement this as not Z (space or separator) and not C (other), except for Cf (format) with a few exceptions. This seems to be what Perl does. The exceptional characters are: U+061C Arabic Letter Mark U+180E Mongolian Vowel Separator U+2066 - U+2069 Various "isolate"s */ case PT_PXGRAPH: if ((PRIV(ucp_gentype)[prop->chartype] != ucp_Z && (PRIV(ucp_gentype)[prop->chartype] != ucp_C || (prop->chartype == ucp_Cf && c != 0x061c && c != 0x180e && (c < 0x2066 || c > 0x2069)) )) == isprop) return !negated; break; /* Printable character: same as graphic, with the addition of Zs, i.e. not Zl and not Zp, and U+180E. */ case PT_PXPRINT: if ((prop->chartype != ucp_Zl && prop->chartype != ucp_Zp && (PRIV(ucp_gentype)[prop->chartype] != ucp_C || (prop->chartype == ucp_Cf && c != 0x061c && (c < 0x2066 || c > 0x2069)) )) == isprop) return !negated; break; /* Punctuation: all Unicode punctuation, plus ASCII characters that Unicode treats as symbols rather than punctuation, for Perl compatibility (these are $+<=>^`|~). */ case PT_PXPUNCT: if ((PRIV(ucp_gentype)[prop->chartype] == ucp_P || (c < 128 && PRIV(ucp_gentype)[prop->chartype] == ucp_S)) == isprop) return !negated; break; /* This should never occur, but compilers may mutter if there is no default. */ default: return FALSE; } data += 2; } #endif /* SUPPORT_UCP */ } return negated; /* char did not match */ } /* End of pcre_xclass.c */
libgit2-main
deps/pcre/pcre_xclass.c
/* This module is generated by the maint/MultiStage2.py script. Do not modify it by hand. Instead modify the script and run it to regenerate this code. As well as being part of the PCRE library, this module is #included by the pcretest program, which redefines the PRIV macro to change table names from _pcre_xxx to xxxx, thereby avoiding name clashes with the library. At present, just one of these tables is actually needed. */ #ifndef PCRE_INCLUDED #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre_internal.h" #endif /* PCRE_INCLUDED */ /* Unicode character database. */ /* This file was autogenerated by the MultiStage2.py script. */ /* Total size: 72576 bytes, block size: 128. */ /* The tables herein are needed only when UCP support is built into PCRE. This module should not be referenced otherwise, so it should not matter whether it is compiled or not. However a comment was received about space saving - maybe the guy linked all the modules rather than using a library - so we include a condition to cut out the tables when not needed. But don't leave a totally empty module because some compilers barf at that. Instead, just supply small dummy tables. */ #ifndef SUPPORT_UCP const ucd_record PRIV(ucd_records)[] = {{0,0,0,0,0 }}; const pcre_uint8 PRIV(ucd_stage1)[] = {0}; const pcre_uint16 PRIV(ucd_stage2)[] = {0}; const pcre_uint32 PRIV(ucd_caseless_sets)[] = {0}; #else /* If the 32-bit library is run in non-32-bit mode, character values greater than 0x10ffff may be encountered. For these we set up a special record. */ #ifdef COMPILE_PCRE32 const ucd_record PRIV(dummy_ucd_record)[] = {{ ucp_Common, /* script */ ucp_Cn, /* type unassigned */ ucp_gbOther, /* grapheme break property */ 0, /* case set */ 0, /* other case */ }}; #endif /* When recompiling tables with a new Unicode version, please check the types in this structure definition from pcre_internal.h (the actual field names will be different): typedef struct { pcre_uint8 property_0; pcre_uint8 property_1; pcre_uint8 property_2; pcre_uint8 property_3; pcre_int32 property_4; } ucd_record; */ const pcre_uint32 PRIV(ucd_caseless_sets)[] = { NOTACHAR, 0x0053, 0x0073, 0x017f, NOTACHAR, 0x01c4, 0x01c5, 0x01c6, NOTACHAR, 0x01c7, 0x01c8, 0x01c9, NOTACHAR, 0x01ca, 0x01cb, 0x01cc, NOTACHAR, 0x01f1, 0x01f2, 0x01f3, NOTACHAR, 0x0345, 0x0399, 0x03b9, 0x1fbe, NOTACHAR, 0x00b5, 0x039c, 0x03bc, NOTACHAR, 0x03a3, 0x03c2, 0x03c3, NOTACHAR, 0x0392, 0x03b2, 0x03d0, NOTACHAR, 0x0398, 0x03b8, 0x03d1, 0x03f4, NOTACHAR, 0x03a6, 0x03c6, 0x03d5, NOTACHAR, 0x03a0, 0x03c0, 0x03d6, NOTACHAR, 0x039a, 0x03ba, 0x03f0, NOTACHAR, 0x03a1, 0x03c1, 0x03f1, NOTACHAR, 0x0395, 0x03b5, 0x03f5, NOTACHAR, 0x1e60, 0x1e61, 0x1e9b, NOTACHAR, 0x03a9, 0x03c9, 0x2126, NOTACHAR, 0x004b, 0x006b, 0x212a, NOTACHAR, 0x00c5, 0x00e5, 0x212b, NOTACHAR, }; /* When #included in pcretest, we don't need this large table. */ #ifndef PCRE_INCLUDED const ucd_record PRIV(ucd_records)[] = { /* 5760 bytes, record size 8 */ { 9, 0, 2, 0, 0, }, /* 0 */ { 9, 0, 1, 0, 0, }, /* 1 */ { 9, 0, 0, 0, 0, }, /* 2 */ { 9, 29, 12, 0, 0, }, /* 3 */ { 9, 21, 12, 0, 0, }, /* 4 */ { 9, 23, 12, 0, 0, }, /* 5 */ { 9, 22, 12, 0, 0, }, /* 6 */ { 9, 18, 12, 0, 0, }, /* 7 */ { 9, 25, 12, 0, 0, }, /* 8 */ { 9, 17, 12, 0, 0, }, /* 9 */ { 9, 13, 12, 0, 0, }, /* 10 */ { 33, 9, 12, 0, 32, }, /* 11 */ { 33, 9, 12, 71, 32, }, /* 12 */ { 33, 9, 12, 1, 32, }, /* 13 */ { 9, 24, 12, 0, 0, }, /* 14 */ { 9, 16, 12, 0, 0, }, /* 15 */ { 33, 5, 12, 0, -32, }, /* 16 */ { 33, 5, 12, 71, -32, }, /* 17 */ { 33, 5, 12, 1, -32, }, /* 18 */ { 9, 26, 12, 0, 0, }, /* 19 */ { 33, 7, 12, 0, 0, }, /* 20 */ { 9, 20, 12, 0, 0, }, /* 21 */ { 9, 1, 2, 0, 0, }, /* 22 */ { 9, 15, 12, 0, 0, }, /* 23 */ { 9, 5, 12, 26, 775, }, /* 24 */ { 9, 19, 12, 0, 0, }, /* 25 */ { 33, 9, 12, 75, 32, }, /* 26 */ { 33, 5, 12, 0, 7615, }, /* 27 */ { 33, 5, 12, 75, -32, }, /* 28 */ { 33, 5, 12, 0, 121, }, /* 29 */ { 33, 9, 12, 0, 1, }, /* 30 */ { 33, 5, 12, 0, -1, }, /* 31 */ { 33, 9, 12, 0, 0, }, /* 32 */ { 33, 5, 12, 0, 0, }, /* 33 */ { 33, 9, 12, 0, -121, }, /* 34 */ { 33, 5, 12, 1, -268, }, /* 35 */ { 33, 5, 12, 0, 195, }, /* 36 */ { 33, 9, 12, 0, 210, }, /* 37 */ { 33, 9, 12, 0, 206, }, /* 38 */ { 33, 9, 12, 0, 205, }, /* 39 */ { 33, 9, 12, 0, 79, }, /* 40 */ { 33, 9, 12, 0, 202, }, /* 41 */ { 33, 9, 12, 0, 203, }, /* 42 */ { 33, 9, 12, 0, 207, }, /* 43 */ { 33, 5, 12, 0, 97, }, /* 44 */ { 33, 9, 12, 0, 211, }, /* 45 */ { 33, 9, 12, 0, 209, }, /* 46 */ { 33, 5, 12, 0, 163, }, /* 47 */ { 33, 9, 12, 0, 213, }, /* 48 */ { 33, 5, 12, 0, 130, }, /* 49 */ { 33, 9, 12, 0, 214, }, /* 50 */ { 33, 9, 12, 0, 218, }, /* 51 */ { 33, 9, 12, 0, 217, }, /* 52 */ { 33, 9, 12, 0, 219, }, /* 53 */ { 33, 5, 12, 0, 56, }, /* 54 */ { 33, 9, 12, 5, 2, }, /* 55 */ { 33, 8, 12, 5, 1, }, /* 56 */ { 33, 5, 12, 5, -2, }, /* 57 */ { 33, 9, 12, 9, 2, }, /* 58 */ { 33, 8, 12, 9, 1, }, /* 59 */ { 33, 5, 12, 9, -2, }, /* 60 */ { 33, 9, 12, 13, 2, }, /* 61 */ { 33, 8, 12, 13, 1, }, /* 62 */ { 33, 5, 12, 13, -2, }, /* 63 */ { 33, 5, 12, 0, -79, }, /* 64 */ { 33, 9, 12, 17, 2, }, /* 65 */ { 33, 8, 12, 17, 1, }, /* 66 */ { 33, 5, 12, 17, -2, }, /* 67 */ { 33, 9, 12, 0, -97, }, /* 68 */ { 33, 9, 12, 0, -56, }, /* 69 */ { 33, 9, 12, 0, -130, }, /* 70 */ { 33, 9, 12, 0, 10795, }, /* 71 */ { 33, 9, 12, 0, -163, }, /* 72 */ { 33, 9, 12, 0, 10792, }, /* 73 */ { 33, 5, 12, 0, 10815, }, /* 74 */ { 33, 9, 12, 0, -195, }, /* 75 */ { 33, 9, 12, 0, 69, }, /* 76 */ { 33, 9, 12, 0, 71, }, /* 77 */ { 33, 5, 12, 0, 10783, }, /* 78 */ { 33, 5, 12, 0, 10780, }, /* 79 */ { 33, 5, 12, 0, 10782, }, /* 80 */ { 33, 5, 12, 0, -210, }, /* 81 */ { 33, 5, 12, 0, -206, }, /* 82 */ { 33, 5, 12, 0, -205, }, /* 83 */ { 33, 5, 12, 0, -202, }, /* 84 */ { 33, 5, 12, 0, -203, }, /* 85 */ { 33, 5, 12, 0, 42319, }, /* 86 */ { 33, 5, 12, 0, 42315, }, /* 87 */ { 33, 5, 12, 0, -207, }, /* 88 */ { 33, 5, 12, 0, 42280, }, /* 89 */ { 33, 5, 12, 0, 42308, }, /* 90 */ { 33, 5, 12, 0, -209, }, /* 91 */ { 33, 5, 12, 0, -211, }, /* 92 */ { 33, 5, 12, 0, 10743, }, /* 93 */ { 33, 5, 12, 0, 42305, }, /* 94 */ { 33, 5, 12, 0, 10749, }, /* 95 */ { 33, 5, 12, 0, -213, }, /* 96 */ { 33, 5, 12, 0, -214, }, /* 97 */ { 33, 5, 12, 0, 10727, }, /* 98 */ { 33, 5, 12, 0, -218, }, /* 99 */ { 33, 5, 12, 0, 42282, }, /* 100 */ { 33, 5, 12, 0, -69, }, /* 101 */ { 33, 5, 12, 0, -217, }, /* 102 */ { 33, 5, 12, 0, -71, }, /* 103 */ { 33, 5, 12, 0, -219, }, /* 104 */ { 33, 5, 12, 0, 42258, }, /* 105 */ { 33, 6, 12, 0, 0, }, /* 106 */ { 9, 6, 12, 0, 0, }, /* 107 */ { 3, 24, 12, 0, 0, }, /* 108 */ { 27, 12, 3, 0, 0, }, /* 109 */ { 27, 12, 3, 21, 116, }, /* 110 */ { 19, 9, 12, 0, 1, }, /* 111 */ { 19, 5, 12, 0, -1, }, /* 112 */ { 19, 24, 12, 0, 0, }, /* 113 */ { 9, 2, 12, 0, 0, }, /* 114 */ { 19, 6, 12, 0, 0, }, /* 115 */ { 19, 5, 12, 0, 130, }, /* 116 */ { 19, 9, 12, 0, 116, }, /* 117 */ { 19, 9, 12, 0, 38, }, /* 118 */ { 19, 9, 12, 0, 37, }, /* 119 */ { 19, 9, 12, 0, 64, }, /* 120 */ { 19, 9, 12, 0, 63, }, /* 121 */ { 19, 5, 12, 0, 0, }, /* 122 */ { 19, 9, 12, 0, 32, }, /* 123 */ { 19, 9, 12, 34, 32, }, /* 124 */ { 19, 9, 12, 59, 32, }, /* 125 */ { 19, 9, 12, 38, 32, }, /* 126 */ { 19, 9, 12, 21, 32, }, /* 127 */ { 19, 9, 12, 51, 32, }, /* 128 */ { 19, 9, 12, 26, 32, }, /* 129 */ { 19, 9, 12, 47, 32, }, /* 130 */ { 19, 9, 12, 55, 32, }, /* 131 */ { 19, 9, 12, 30, 32, }, /* 132 */ { 19, 9, 12, 43, 32, }, /* 133 */ { 19, 9, 12, 67, 32, }, /* 134 */ { 19, 5, 12, 0, -38, }, /* 135 */ { 19, 5, 12, 0, -37, }, /* 136 */ { 19, 5, 12, 0, -32, }, /* 137 */ { 19, 5, 12, 34, -32, }, /* 138 */ { 19, 5, 12, 59, -32, }, /* 139 */ { 19, 5, 12, 38, -32, }, /* 140 */ { 19, 5, 12, 21, -116, }, /* 141 */ { 19, 5, 12, 51, -32, }, /* 142 */ { 19, 5, 12, 26, -775, }, /* 143 */ { 19, 5, 12, 47, -32, }, /* 144 */ { 19, 5, 12, 55, -32, }, /* 145 */ { 19, 5, 12, 30, 1, }, /* 146 */ { 19, 5, 12, 30, -32, }, /* 147 */ { 19, 5, 12, 43, -32, }, /* 148 */ { 19, 5, 12, 67, -32, }, /* 149 */ { 19, 5, 12, 0, -64, }, /* 150 */ { 19, 5, 12, 0, -63, }, /* 151 */ { 19, 9, 12, 0, 8, }, /* 152 */ { 19, 5, 12, 34, -30, }, /* 153 */ { 19, 5, 12, 38, -25, }, /* 154 */ { 19, 9, 12, 0, 0, }, /* 155 */ { 19, 5, 12, 43, -15, }, /* 156 */ { 19, 5, 12, 47, -22, }, /* 157 */ { 19, 5, 12, 0, -8, }, /* 158 */ { 10, 9, 12, 0, 1, }, /* 159 */ { 10, 5, 12, 0, -1, }, /* 160 */ { 19, 5, 12, 51, -54, }, /* 161 */ { 19, 5, 12, 55, -48, }, /* 162 */ { 19, 5, 12, 0, 7, }, /* 163 */ { 19, 5, 12, 0, -116, }, /* 164 */ { 19, 9, 12, 38, -60, }, /* 165 */ { 19, 5, 12, 59, -64, }, /* 166 */ { 19, 25, 12, 0, 0, }, /* 167 */ { 19, 9, 12, 0, -7, }, /* 168 */ { 19, 9, 12, 0, -130, }, /* 169 */ { 12, 9, 12, 0, 80, }, /* 170 */ { 12, 9, 12, 0, 32, }, /* 171 */ { 12, 5, 12, 0, -32, }, /* 172 */ { 12, 5, 12, 0, -80, }, /* 173 */ { 12, 9, 12, 0, 1, }, /* 174 */ { 12, 5, 12, 0, -1, }, /* 175 */ { 12, 26, 12, 0, 0, }, /* 176 */ { 12, 12, 3, 0, 0, }, /* 177 */ { 12, 11, 3, 0, 0, }, /* 178 */ { 12, 9, 12, 0, 15, }, /* 179 */ { 12, 5, 12, 0, -15, }, /* 180 */ { 1, 9, 12, 0, 48, }, /* 181 */ { 1, 6, 12, 0, 0, }, /* 182 */ { 1, 21, 12, 0, 0, }, /* 183 */ { 1, 5, 12, 0, -48, }, /* 184 */ { 1, 5, 12, 0, 0, }, /* 185 */ { 1, 17, 12, 0, 0, }, /* 186 */ { 1, 26, 12, 0, 0, }, /* 187 */ { 1, 23, 12, 0, 0, }, /* 188 */ { 25, 12, 3, 0, 0, }, /* 189 */ { 25, 17, 12, 0, 0, }, /* 190 */ { 25, 21, 12, 0, 0, }, /* 191 */ { 25, 7, 12, 0, 0, }, /* 192 */ { 0, 1, 2, 0, 0, }, /* 193 */ { 0, 25, 12, 0, 0, }, /* 194 */ { 0, 21, 12, 0, 0, }, /* 195 */ { 0, 23, 12, 0, 0, }, /* 196 */ { 0, 26, 12, 0, 0, }, /* 197 */ { 0, 12, 3, 0, 0, }, /* 198 */ { 0, 7, 12, 0, 0, }, /* 199 */ { 0, 6, 12, 0, 0, }, /* 200 */ { 0, 13, 12, 0, 0, }, /* 201 */ { 49, 21, 12, 0, 0, }, /* 202 */ { 49, 1, 2, 0, 0, }, /* 203 */ { 49, 7, 12, 0, 0, }, /* 204 */ { 49, 12, 3, 0, 0, }, /* 205 */ { 55, 7, 12, 0, 0, }, /* 206 */ { 55, 12, 3, 0, 0, }, /* 207 */ { 63, 13, 12, 0, 0, }, /* 208 */ { 63, 7, 12, 0, 0, }, /* 209 */ { 63, 12, 3, 0, 0, }, /* 210 */ { 63, 6, 12, 0, 0, }, /* 211 */ { 63, 26, 12, 0, 0, }, /* 212 */ { 63, 21, 12, 0, 0, }, /* 213 */ { 89, 7, 12, 0, 0, }, /* 214 */ { 89, 12, 3, 0, 0, }, /* 215 */ { 89, 6, 12, 0, 0, }, /* 216 */ { 89, 21, 12, 0, 0, }, /* 217 */ { 94, 7, 12, 0, 0, }, /* 218 */ { 94, 12, 3, 0, 0, }, /* 219 */ { 94, 21, 12, 0, 0, }, /* 220 */ { 14, 12, 3, 0, 0, }, /* 221 */ { 14, 10, 5, 0, 0, }, /* 222 */ { 14, 7, 12, 0, 0, }, /* 223 */ { 14, 13, 12, 0, 0, }, /* 224 */ { 14, 21, 12, 0, 0, }, /* 225 */ { 14, 6, 12, 0, 0, }, /* 226 */ { 2, 7, 12, 0, 0, }, /* 227 */ { 2, 12, 3, 0, 0, }, /* 228 */ { 2, 10, 5, 0, 0, }, /* 229 */ { 2, 10, 3, 0, 0, }, /* 230 */ { 2, 13, 12, 0, 0, }, /* 231 */ { 2, 23, 12, 0, 0, }, /* 232 */ { 2, 15, 12, 0, 0, }, /* 233 */ { 2, 26, 12, 0, 0, }, /* 234 */ { 21, 12, 3, 0, 0, }, /* 235 */ { 21, 10, 5, 0, 0, }, /* 236 */ { 21, 7, 12, 0, 0, }, /* 237 */ { 21, 13, 12, 0, 0, }, /* 238 */ { 20, 12, 3, 0, 0, }, /* 239 */ { 20, 10, 5, 0, 0, }, /* 240 */ { 20, 7, 12, 0, 0, }, /* 241 */ { 20, 13, 12, 0, 0, }, /* 242 */ { 20, 21, 12, 0, 0, }, /* 243 */ { 20, 23, 12, 0, 0, }, /* 244 */ { 43, 12, 3, 0, 0, }, /* 245 */ { 43, 10, 5, 0, 0, }, /* 246 */ { 43, 7, 12, 0, 0, }, /* 247 */ { 43, 10, 3, 0, 0, }, /* 248 */ { 43, 13, 12, 0, 0, }, /* 249 */ { 43, 26, 12, 0, 0, }, /* 250 */ { 43, 15, 12, 0, 0, }, /* 251 */ { 53, 12, 3, 0, 0, }, /* 252 */ { 53, 7, 12, 0, 0, }, /* 253 */ { 53, 10, 3, 0, 0, }, /* 254 */ { 53, 10, 5, 0, 0, }, /* 255 */ { 53, 13, 12, 0, 0, }, /* 256 */ { 53, 15, 12, 0, 0, }, /* 257 */ { 53, 26, 12, 0, 0, }, /* 258 */ { 53, 23, 12, 0, 0, }, /* 259 */ { 54, 12, 3, 0, 0, }, /* 260 */ { 54, 10, 5, 0, 0, }, /* 261 */ { 54, 7, 12, 0, 0, }, /* 262 */ { 54, 13, 12, 0, 0, }, /* 263 */ { 54, 15, 12, 0, 0, }, /* 264 */ { 54, 26, 12, 0, 0, }, /* 265 */ { 28, 12, 3, 0, 0, }, /* 266 */ { 28, 10, 5, 0, 0, }, /* 267 */ { 28, 7, 12, 0, 0, }, /* 268 */ { 28, 10, 3, 0, 0, }, /* 269 */ { 28, 13, 12, 0, 0, }, /* 270 */ { 36, 12, 3, 0, 0, }, /* 271 */ { 36, 10, 5, 0, 0, }, /* 272 */ { 36, 7, 12, 0, 0, }, /* 273 */ { 36, 10, 3, 0, 0, }, /* 274 */ { 36, 13, 12, 0, 0, }, /* 275 */ { 36, 15, 12, 0, 0, }, /* 276 */ { 36, 26, 12, 0, 0, }, /* 277 */ { 47, 10, 5, 0, 0, }, /* 278 */ { 47, 7, 12, 0, 0, }, /* 279 */ { 47, 12, 3, 0, 0, }, /* 280 */ { 47, 10, 3, 0, 0, }, /* 281 */ { 47, 13, 12, 0, 0, }, /* 282 */ { 47, 21, 12, 0, 0, }, /* 283 */ { 56, 7, 12, 0, 0, }, /* 284 */ { 56, 12, 3, 0, 0, }, /* 285 */ { 56, 7, 5, 0, 0, }, /* 286 */ { 56, 6, 12, 0, 0, }, /* 287 */ { 56, 21, 12, 0, 0, }, /* 288 */ { 56, 13, 12, 0, 0, }, /* 289 */ { 32, 7, 12, 0, 0, }, /* 290 */ { 32, 12, 3, 0, 0, }, /* 291 */ { 32, 7, 5, 0, 0, }, /* 292 */ { 32, 6, 12, 0, 0, }, /* 293 */ { 32, 13, 12, 0, 0, }, /* 294 */ { 57, 7, 12, 0, 0, }, /* 295 */ { 57, 26, 12, 0, 0, }, /* 296 */ { 57, 21, 12, 0, 0, }, /* 297 */ { 57, 12, 3, 0, 0, }, /* 298 */ { 57, 13, 12, 0, 0, }, /* 299 */ { 57, 15, 12, 0, 0, }, /* 300 */ { 57, 22, 12, 0, 0, }, /* 301 */ { 57, 18, 12, 0, 0, }, /* 302 */ { 57, 10, 5, 0, 0, }, /* 303 */ { 38, 7, 12, 0, 0, }, /* 304 */ { 38, 10, 12, 0, 0, }, /* 305 */ { 38, 12, 3, 0, 0, }, /* 306 */ { 38, 10, 5, 0, 0, }, /* 307 */ { 38, 13, 12, 0, 0, }, /* 308 */ { 38, 21, 12, 0, 0, }, /* 309 */ { 38, 26, 12, 0, 0, }, /* 310 */ { 16, 9, 12, 0, 7264, }, /* 311 */ { 16, 7, 12, 0, 0, }, /* 312 */ { 16, 6, 12, 0, 0, }, /* 313 */ { 23, 7, 6, 0, 0, }, /* 314 */ { 23, 7, 7, 0, 0, }, /* 315 */ { 23, 7, 8, 0, 0, }, /* 316 */ { 15, 7, 12, 0, 0, }, /* 317 */ { 15, 12, 3, 0, 0, }, /* 318 */ { 15, 21, 12, 0, 0, }, /* 319 */ { 15, 15, 12, 0, 0, }, /* 320 */ { 15, 26, 12, 0, 0, }, /* 321 */ { 8, 7, 12, 0, 0, }, /* 322 */ { 7, 17, 12, 0, 0, }, /* 323 */ { 7, 7, 12, 0, 0, }, /* 324 */ { 7, 21, 12, 0, 0, }, /* 325 */ { 40, 29, 12, 0, 0, }, /* 326 */ { 40, 7, 12, 0, 0, }, /* 327 */ { 40, 22, 12, 0, 0, }, /* 328 */ { 40, 18, 12, 0, 0, }, /* 329 */ { 45, 7, 12, 0, 0, }, /* 330 */ { 45, 14, 12, 0, 0, }, /* 331 */ { 50, 7, 12, 0, 0, }, /* 332 */ { 50, 12, 3, 0, 0, }, /* 333 */ { 24, 7, 12, 0, 0, }, /* 334 */ { 24, 12, 3, 0, 0, }, /* 335 */ { 6, 7, 12, 0, 0, }, /* 336 */ { 6, 12, 3, 0, 0, }, /* 337 */ { 51, 7, 12, 0, 0, }, /* 338 */ { 51, 12, 3, 0, 0, }, /* 339 */ { 31, 7, 12, 0, 0, }, /* 340 */ { 31, 12, 3, 0, 0, }, /* 341 */ { 31, 10, 5, 0, 0, }, /* 342 */ { 31, 21, 12, 0, 0, }, /* 343 */ { 31, 6, 12, 0, 0, }, /* 344 */ { 31, 23, 12, 0, 0, }, /* 345 */ { 31, 13, 12, 0, 0, }, /* 346 */ { 31, 15, 12, 0, 0, }, /* 347 */ { 37, 21, 12, 0, 0, }, /* 348 */ { 37, 17, 12, 0, 0, }, /* 349 */ { 37, 12, 3, 0, 0, }, /* 350 */ { 37, 1, 2, 0, 0, }, /* 351 */ { 37, 13, 12, 0, 0, }, /* 352 */ { 37, 7, 12, 0, 0, }, /* 353 */ { 37, 6, 12, 0, 0, }, /* 354 */ { 34, 7, 12, 0, 0, }, /* 355 */ { 34, 12, 3, 0, 0, }, /* 356 */ { 34, 10, 5, 0, 0, }, /* 357 */ { 34, 26, 12, 0, 0, }, /* 358 */ { 34, 21, 12, 0, 0, }, /* 359 */ { 34, 13, 12, 0, 0, }, /* 360 */ { 52, 7, 12, 0, 0, }, /* 361 */ { 39, 7, 12, 0, 0, }, /* 362 */ { 39, 10, 12, 0, 0, }, /* 363 */ { 39, 10, 5, 0, 0, }, /* 364 */ { 39, 13, 12, 0, 0, }, /* 365 */ { 39, 15, 12, 0, 0, }, /* 366 */ { 39, 26, 12, 0, 0, }, /* 367 */ { 31, 26, 12, 0, 0, }, /* 368 */ { 5, 7, 12, 0, 0, }, /* 369 */ { 5, 12, 3, 0, 0, }, /* 370 */ { 5, 10, 5, 0, 0, }, /* 371 */ { 5, 21, 12, 0, 0, }, /* 372 */ { 90, 7, 12, 0, 0, }, /* 373 */ { 90, 10, 5, 0, 0, }, /* 374 */ { 90, 12, 3, 0, 0, }, /* 375 */ { 90, 10, 12, 0, 0, }, /* 376 */ { 90, 13, 12, 0, 0, }, /* 377 */ { 90, 21, 12, 0, 0, }, /* 378 */ { 90, 6, 12, 0, 0, }, /* 379 */ { 27, 11, 3, 0, 0, }, /* 380 */ { 61, 12, 3, 0, 0, }, /* 381 */ { 61, 10, 5, 0, 0, }, /* 382 */ { 61, 7, 12, 0, 0, }, /* 383 */ { 61, 13, 12, 0, 0, }, /* 384 */ { 61, 21, 12, 0, 0, }, /* 385 */ { 61, 26, 12, 0, 0, }, /* 386 */ { 75, 12, 3, 0, 0, }, /* 387 */ { 75, 10, 5, 0, 0, }, /* 388 */ { 75, 7, 12, 0, 0, }, /* 389 */ { 75, 13, 12, 0, 0, }, /* 390 */ { 92, 7, 12, 0, 0, }, /* 391 */ { 92, 12, 3, 0, 0, }, /* 392 */ { 92, 10, 5, 0, 0, }, /* 393 */ { 92, 21, 12, 0, 0, }, /* 394 */ { 69, 7, 12, 0, 0, }, /* 395 */ { 69, 10, 5, 0, 0, }, /* 396 */ { 69, 12, 3, 0, 0, }, /* 397 */ { 69, 21, 12, 0, 0, }, /* 398 */ { 69, 13, 12, 0, 0, }, /* 399 */ { 72, 13, 12, 0, 0, }, /* 400 */ { 72, 7, 12, 0, 0, }, /* 401 */ { 72, 6, 12, 0, 0, }, /* 402 */ { 72, 21, 12, 0, 0, }, /* 403 */ { 75, 21, 12, 0, 0, }, /* 404 */ { 9, 10, 5, 0, 0, }, /* 405 */ { 9, 7, 12, 0, 0, }, /* 406 */ { 12, 5, 12, 0, 0, }, /* 407 */ { 12, 6, 12, 0, 0, }, /* 408 */ { 33, 5, 12, 0, 35332, }, /* 409 */ { 33, 5, 12, 0, 3814, }, /* 410 */ { 33, 9, 12, 63, 1, }, /* 411 */ { 33, 5, 12, 63, -1, }, /* 412 */ { 33, 5, 12, 63, -58, }, /* 413 */ { 33, 9, 12, 0, -7615, }, /* 414 */ { 19, 5, 12, 0, 8, }, /* 415 */ { 19, 9, 12, 0, -8, }, /* 416 */ { 19, 5, 12, 0, 74, }, /* 417 */ { 19, 5, 12, 0, 86, }, /* 418 */ { 19, 5, 12, 0, 100, }, /* 419 */ { 19, 5, 12, 0, 128, }, /* 420 */ { 19, 5, 12, 0, 112, }, /* 421 */ { 19, 5, 12, 0, 126, }, /* 422 */ { 19, 8, 12, 0, -8, }, /* 423 */ { 19, 5, 12, 0, 9, }, /* 424 */ { 19, 9, 12, 0, -74, }, /* 425 */ { 19, 8, 12, 0, -9, }, /* 426 */ { 19, 5, 12, 21, -7173, }, /* 427 */ { 19, 9, 12, 0, -86, }, /* 428 */ { 19, 9, 12, 0, -100, }, /* 429 */ { 19, 9, 12, 0, -112, }, /* 430 */ { 19, 9, 12, 0, -128, }, /* 431 */ { 19, 9, 12, 0, -126, }, /* 432 */ { 27, 1, 3, 0, 0, }, /* 433 */ { 9, 27, 2, 0, 0, }, /* 434 */ { 9, 28, 2, 0, 0, }, /* 435 */ { 9, 2, 2, 0, 0, }, /* 436 */ { 9, 9, 12, 0, 0, }, /* 437 */ { 9, 5, 12, 0, 0, }, /* 438 */ { 19, 9, 12, 67, -7517, }, /* 439 */ { 33, 9, 12, 71, -8383, }, /* 440 */ { 33, 9, 12, 75, -8262, }, /* 441 */ { 33, 9, 12, 0, 28, }, /* 442 */ { 33, 5, 12, 0, -28, }, /* 443 */ { 33, 14, 12, 0, 16, }, /* 444 */ { 33, 14, 12, 0, -16, }, /* 445 */ { 33, 14, 12, 0, 0, }, /* 446 */ { 9, 26, 12, 0, 26, }, /* 447 */ { 9, 26, 12, 0, -26, }, /* 448 */ { 4, 26, 12, 0, 0, }, /* 449 */ { 17, 9, 12, 0, 48, }, /* 450 */ { 17, 5, 12, 0, -48, }, /* 451 */ { 33, 9, 12, 0, -10743, }, /* 452 */ { 33, 9, 12, 0, -3814, }, /* 453 */ { 33, 9, 12, 0, -10727, }, /* 454 */ { 33, 5, 12, 0, -10795, }, /* 455 */ { 33, 5, 12, 0, -10792, }, /* 456 */ { 33, 9, 12, 0, -10780, }, /* 457 */ { 33, 9, 12, 0, -10749, }, /* 458 */ { 33, 9, 12, 0, -10783, }, /* 459 */ { 33, 9, 12, 0, -10782, }, /* 460 */ { 33, 9, 12, 0, -10815, }, /* 461 */ { 10, 5, 12, 0, 0, }, /* 462 */ { 10, 26, 12, 0, 0, }, /* 463 */ { 10, 12, 3, 0, 0, }, /* 464 */ { 10, 21, 12, 0, 0, }, /* 465 */ { 10, 15, 12, 0, 0, }, /* 466 */ { 16, 5, 12, 0, -7264, }, /* 467 */ { 58, 7, 12, 0, 0, }, /* 468 */ { 58, 6, 12, 0, 0, }, /* 469 */ { 58, 21, 12, 0, 0, }, /* 470 */ { 58, 12, 3, 0, 0, }, /* 471 */ { 22, 26, 12, 0, 0, }, /* 472 */ { 22, 6, 12, 0, 0, }, /* 473 */ { 22, 14, 12, 0, 0, }, /* 474 */ { 23, 10, 3, 0, 0, }, /* 475 */ { 26, 7, 12, 0, 0, }, /* 476 */ { 26, 6, 12, 0, 0, }, /* 477 */ { 29, 7, 12, 0, 0, }, /* 478 */ { 29, 6, 12, 0, 0, }, /* 479 */ { 3, 7, 12, 0, 0, }, /* 480 */ { 23, 7, 12, 0, 0, }, /* 481 */ { 23, 26, 12, 0, 0, }, /* 482 */ { 29, 26, 12, 0, 0, }, /* 483 */ { 22, 7, 12, 0, 0, }, /* 484 */ { 60, 7, 12, 0, 0, }, /* 485 */ { 60, 6, 12, 0, 0, }, /* 486 */ { 60, 26, 12, 0, 0, }, /* 487 */ { 85, 7, 12, 0, 0, }, /* 488 */ { 85, 6, 12, 0, 0, }, /* 489 */ { 85, 21, 12, 0, 0, }, /* 490 */ { 76, 7, 12, 0, 0, }, /* 491 */ { 76, 6, 12, 0, 0, }, /* 492 */ { 76, 21, 12, 0, 0, }, /* 493 */ { 76, 13, 12, 0, 0, }, /* 494 */ { 12, 7, 12, 0, 0, }, /* 495 */ { 12, 21, 12, 0, 0, }, /* 496 */ { 78, 7, 12, 0, 0, }, /* 497 */ { 78, 14, 12, 0, 0, }, /* 498 */ { 78, 12, 3, 0, 0, }, /* 499 */ { 78, 21, 12, 0, 0, }, /* 500 */ { 33, 9, 12, 0, -35332, }, /* 501 */ { 33, 9, 12, 0, -42280, }, /* 502 */ { 33, 9, 12, 0, -42308, }, /* 503 */ { 33, 9, 12, 0, -42319, }, /* 504 */ { 33, 9, 12, 0, -42315, }, /* 505 */ { 33, 9, 12, 0, -42305, }, /* 506 */ { 33, 9, 12, 0, -42258, }, /* 507 */ { 33, 9, 12, 0, -42282, }, /* 508 */ { 48, 7, 12, 0, 0, }, /* 509 */ { 48, 12, 3, 0, 0, }, /* 510 */ { 48, 10, 5, 0, 0, }, /* 511 */ { 48, 26, 12, 0, 0, }, /* 512 */ { 64, 7, 12, 0, 0, }, /* 513 */ { 64, 21, 12, 0, 0, }, /* 514 */ { 74, 10, 5, 0, 0, }, /* 515 */ { 74, 7, 12, 0, 0, }, /* 516 */ { 74, 12, 3, 0, 0, }, /* 517 */ { 74, 21, 12, 0, 0, }, /* 518 */ { 74, 13, 12, 0, 0, }, /* 519 */ { 68, 13, 12, 0, 0, }, /* 520 */ { 68, 7, 12, 0, 0, }, /* 521 */ { 68, 12, 3, 0, 0, }, /* 522 */ { 68, 21, 12, 0, 0, }, /* 523 */ { 73, 7, 12, 0, 0, }, /* 524 */ { 73, 12, 3, 0, 0, }, /* 525 */ { 73, 10, 5, 0, 0, }, /* 526 */ { 73, 21, 12, 0, 0, }, /* 527 */ { 83, 12, 3, 0, 0, }, /* 528 */ { 83, 10, 5, 0, 0, }, /* 529 */ { 83, 7, 12, 0, 0, }, /* 530 */ { 83, 21, 12, 0, 0, }, /* 531 */ { 83, 13, 12, 0, 0, }, /* 532 */ { 38, 6, 12, 0, 0, }, /* 533 */ { 67, 7, 12, 0, 0, }, /* 534 */ { 67, 12, 3, 0, 0, }, /* 535 */ { 67, 10, 5, 0, 0, }, /* 536 */ { 67, 13, 12, 0, 0, }, /* 537 */ { 67, 21, 12, 0, 0, }, /* 538 */ { 91, 7, 12, 0, 0, }, /* 539 */ { 91, 12, 3, 0, 0, }, /* 540 */ { 91, 6, 12, 0, 0, }, /* 541 */ { 91, 21, 12, 0, 0, }, /* 542 */ { 86, 7, 12, 0, 0, }, /* 543 */ { 86, 10, 5, 0, 0, }, /* 544 */ { 86, 12, 3, 0, 0, }, /* 545 */ { 86, 21, 12, 0, 0, }, /* 546 */ { 86, 6, 12, 0, 0, }, /* 547 */ { 86, 13, 12, 0, 0, }, /* 548 */ { 23, 7, 9, 0, 0, }, /* 549 */ { 23, 7, 10, 0, 0, }, /* 550 */ { 9, 4, 2, 0, 0, }, /* 551 */ { 9, 3, 12, 0, 0, }, /* 552 */ { 25, 25, 12, 0, 0, }, /* 553 */ { 0, 24, 12, 0, 0, }, /* 554 */ { 9, 6, 3, 0, 0, }, /* 555 */ { 35, 7, 12, 0, 0, }, /* 556 */ { 19, 14, 12, 0, 0, }, /* 557 */ { 19, 15, 12, 0, 0, }, /* 558 */ { 19, 26, 12, 0, 0, }, /* 559 */ { 70, 7, 12, 0, 0, }, /* 560 */ { 66, 7, 12, 0, 0, }, /* 561 */ { 41, 7, 12, 0, 0, }, /* 562 */ { 41, 15, 12, 0, 0, }, /* 563 */ { 18, 7, 12, 0, 0, }, /* 564 */ { 18, 14, 12, 0, 0, }, /* 565 */ { 117, 7, 12, 0, 0, }, /* 566 */ { 117, 12, 3, 0, 0, }, /* 567 */ { 59, 7, 12, 0, 0, }, /* 568 */ { 59, 21, 12, 0, 0, }, /* 569 */ { 42, 7, 12, 0, 0, }, /* 570 */ { 42, 21, 12, 0, 0, }, /* 571 */ { 42, 14, 12, 0, 0, }, /* 572 */ { 13, 9, 12, 0, 40, }, /* 573 */ { 13, 5, 12, 0, -40, }, /* 574 */ { 46, 7, 12, 0, 0, }, /* 575 */ { 44, 7, 12, 0, 0, }, /* 576 */ { 44, 13, 12, 0, 0, }, /* 577 */ { 105, 7, 12, 0, 0, }, /* 578 */ { 103, 7, 12, 0, 0, }, /* 579 */ { 103, 21, 12, 0, 0, }, /* 580 */ { 109, 7, 12, 0, 0, }, /* 581 */ { 11, 7, 12, 0, 0, }, /* 582 */ { 80, 7, 12, 0, 0, }, /* 583 */ { 80, 21, 12, 0, 0, }, /* 584 */ { 80, 15, 12, 0, 0, }, /* 585 */ { 119, 7, 12, 0, 0, }, /* 586 */ { 119, 26, 12, 0, 0, }, /* 587 */ { 119, 15, 12, 0, 0, }, /* 588 */ { 115, 7, 12, 0, 0, }, /* 589 */ { 115, 15, 12, 0, 0, }, /* 590 */ { 65, 7, 12, 0, 0, }, /* 591 */ { 65, 15, 12, 0, 0, }, /* 592 */ { 65, 21, 12, 0, 0, }, /* 593 */ { 71, 7, 12, 0, 0, }, /* 594 */ { 71, 21, 12, 0, 0, }, /* 595 */ { 97, 7, 12, 0, 0, }, /* 596 */ { 96, 7, 12, 0, 0, }, /* 597 */ { 30, 7, 12, 0, 0, }, /* 598 */ { 30, 12, 3, 0, 0, }, /* 599 */ { 30, 15, 12, 0, 0, }, /* 600 */ { 30, 21, 12, 0, 0, }, /* 601 */ { 87, 7, 12, 0, 0, }, /* 602 */ { 87, 15, 12, 0, 0, }, /* 603 */ { 87, 21, 12, 0, 0, }, /* 604 */ { 116, 7, 12, 0, 0, }, /* 605 */ { 116, 15, 12, 0, 0, }, /* 606 */ { 111, 7, 12, 0, 0, }, /* 607 */ { 111, 26, 12, 0, 0, }, /* 608 */ { 111, 12, 3, 0, 0, }, /* 609 */ { 111, 15, 12, 0, 0, }, /* 610 */ { 111, 21, 12, 0, 0, }, /* 611 */ { 77, 7, 12, 0, 0, }, /* 612 */ { 77, 21, 12, 0, 0, }, /* 613 */ { 82, 7, 12, 0, 0, }, /* 614 */ { 82, 15, 12, 0, 0, }, /* 615 */ { 81, 7, 12, 0, 0, }, /* 616 */ { 81, 15, 12, 0, 0, }, /* 617 */ { 120, 7, 12, 0, 0, }, /* 618 */ { 120, 21, 12, 0, 0, }, /* 619 */ { 120, 15, 12, 0, 0, }, /* 620 */ { 88, 7, 12, 0, 0, }, /* 621 */ { 0, 15, 12, 0, 0, }, /* 622 */ { 93, 10, 5, 0, 0, }, /* 623 */ { 93, 12, 3, 0, 0, }, /* 624 */ { 93, 7, 12, 0, 0, }, /* 625 */ { 93, 21, 12, 0, 0, }, /* 626 */ { 93, 15, 12, 0, 0, }, /* 627 */ { 93, 13, 12, 0, 0, }, /* 628 */ { 84, 12, 3, 0, 0, }, /* 629 */ { 84, 10, 5, 0, 0, }, /* 630 */ { 84, 7, 12, 0, 0, }, /* 631 */ { 84, 21, 12, 0, 0, }, /* 632 */ { 84, 1, 2, 0, 0, }, /* 633 */ { 100, 7, 12, 0, 0, }, /* 634 */ { 100, 13, 12, 0, 0, }, /* 635 */ { 95, 12, 3, 0, 0, }, /* 636 */ { 95, 7, 12, 0, 0, }, /* 637 */ { 95, 10, 5, 0, 0, }, /* 638 */ { 95, 13, 12, 0, 0, }, /* 639 */ { 95, 21, 12, 0, 0, }, /* 640 */ { 110, 7, 12, 0, 0, }, /* 641 */ { 110, 12, 3, 0, 0, }, /* 642 */ { 110, 21, 12, 0, 0, }, /* 643 */ { 99, 12, 3, 0, 0, }, /* 644 */ { 99, 10, 5, 0, 0, }, /* 645 */ { 99, 7, 12, 0, 0, }, /* 646 */ { 99, 21, 12, 0, 0, }, /* 647 */ { 99, 13, 12, 0, 0, }, /* 648 */ { 47, 15, 12, 0, 0, }, /* 649 */ { 107, 7, 12, 0, 0, }, /* 650 */ { 107, 10, 5, 0, 0, }, /* 651 */ { 107, 12, 3, 0, 0, }, /* 652 */ { 107, 21, 12, 0, 0, }, /* 653 */ { 108, 7, 12, 0, 0, }, /* 654 */ { 108, 12, 3, 0, 0, }, /* 655 */ { 108, 10, 5, 0, 0, }, /* 656 */ { 108, 13, 12, 0, 0, }, /* 657 */ { 106, 12, 3, 0, 0, }, /* 658 */ { 106, 10, 5, 0, 0, }, /* 659 */ { 106, 7, 12, 0, 0, }, /* 660 */ { 106, 10, 3, 0, 0, }, /* 661 */ { 123, 7, 12, 0, 0, }, /* 662 */ { 123, 10, 3, 0, 0, }, /* 663 */ { 123, 10, 5, 0, 0, }, /* 664 */ { 123, 12, 3, 0, 0, }, /* 665 */ { 123, 21, 12, 0, 0, }, /* 666 */ { 123, 13, 12, 0, 0, }, /* 667 */ { 122, 7, 12, 0, 0, }, /* 668 */ { 122, 10, 3, 0, 0, }, /* 669 */ { 122, 10, 5, 0, 0, }, /* 670 */ { 122, 12, 3, 0, 0, }, /* 671 */ { 122, 21, 12, 0, 0, }, /* 672 */ { 113, 7, 12, 0, 0, }, /* 673 */ { 113, 10, 5, 0, 0, }, /* 674 */ { 113, 12, 3, 0, 0, }, /* 675 */ { 113, 21, 12, 0, 0, }, /* 676 */ { 113, 13, 12, 0, 0, }, /* 677 */ { 101, 7, 12, 0, 0, }, /* 678 */ { 101, 12, 3, 0, 0, }, /* 679 */ { 101, 10, 5, 0, 0, }, /* 680 */ { 101, 13, 12, 0, 0, }, /* 681 */ { 124, 9, 12, 0, 32, }, /* 682 */ { 124, 5, 12, 0, -32, }, /* 683 */ { 124, 13, 12, 0, 0, }, /* 684 */ { 124, 15, 12, 0, 0, }, /* 685 */ { 124, 7, 12, 0, 0, }, /* 686 */ { 121, 7, 12, 0, 0, }, /* 687 */ { 62, 7, 12, 0, 0, }, /* 688 */ { 62, 14, 12, 0, 0, }, /* 689 */ { 62, 21, 12, 0, 0, }, /* 690 */ { 79, 7, 12, 0, 0, }, /* 691 */ { 114, 7, 12, 0, 0, }, /* 692 */ { 114, 13, 12, 0, 0, }, /* 693 */ { 114, 21, 12, 0, 0, }, /* 694 */ { 102, 7, 12, 0, 0, }, /* 695 */ { 102, 12, 3, 0, 0, }, /* 696 */ { 102, 21, 12, 0, 0, }, /* 697 */ { 118, 7, 12, 0, 0, }, /* 698 */ { 118, 12, 3, 0, 0, }, /* 699 */ { 118, 21, 12, 0, 0, }, /* 700 */ { 118, 26, 12, 0, 0, }, /* 701 */ { 118, 6, 12, 0, 0, }, /* 702 */ { 118, 13, 12, 0, 0, }, /* 703 */ { 118, 15, 12, 0, 0, }, /* 704 */ { 98, 7, 12, 0, 0, }, /* 705 */ { 98, 10, 5, 0, 0, }, /* 706 */ { 98, 12, 3, 0, 0, }, /* 707 */ { 98, 6, 12, 0, 0, }, /* 708 */ { 104, 7, 12, 0, 0, }, /* 709 */ { 104, 26, 12, 0, 0, }, /* 710 */ { 104, 12, 3, 0, 0, }, /* 711 */ { 104, 21, 12, 0, 0, }, /* 712 */ { 9, 10, 3, 0, 0, }, /* 713 */ { 19, 12, 3, 0, 0, }, /* 714 */ { 112, 7, 12, 0, 0, }, /* 715 */ { 112, 15, 12, 0, 0, }, /* 716 */ { 112, 12, 3, 0, 0, }, /* 717 */ { 9, 26, 11, 0, 0, }, /* 718 */ { 26, 26, 12, 0, 0, }, /* 719 */ }; const pcre_uint8 PRIV(ucd_stage1)[] = { /* 8704 bytes */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* U+0000 */ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* U+0800 */ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 41, 41, 42, 43, 44, 45, /* U+1000 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /* U+1800 */ 62, 63, 64, 65, 66, 66, 67, 68, 69, 70, 71, 72, 73, 71, 74, 75, /* U+2000 */ 76, 76, 66, 77, 66, 66, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, /* U+2800 */ 88, 89, 90, 91, 92, 93, 94, 71, 95, 95, 95, 95, 95, 95, 95, 95, /* U+3000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+3800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+4000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 96, 95, 95, 95, 95, /* U+4800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+5000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+5800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+6000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+6800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+7000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+7800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+8000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+8800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+9000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 97, /* U+9800 */ 98, 99, 99, 99, 99, 99, 99, 99, 99,100,101,101,102,103,104,105, /* U+A000 */ 106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,114, /* U+A800 */ 115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116, /* U+B000 */ 117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118, /* U+B800 */ 119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120, /* U+C000 */ 114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115, /* U+C800 */ 116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,121, /* U+D000 */ 122,122,122,122,122,122,122,122,122,122,122,122,122,122,122,122, /* U+D800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+E000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+E800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F000 */ 123,123, 95, 95,124,125,126,127,128,128,129,130,131,132,133,134, /* U+F800 */ 135,136,137,138,139,140,141,142,143,144,145,139,146,146,147,139, /* U+10000 */ 148,149,150,151,152,153,154,155,156,139,139,139,157,139,139,139, /* U+10800 */ 158,159,160,161,162,163,164,139,139,165,139,166,167,168,139,139, /* U+11000 */ 139,169,139,139,139,170,139,139,139,139,139,139,139,139,139,139, /* U+11800 */ 171,171,171,171,171,171,171,172,173,139,139,139,139,139,139,139, /* U+12000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+12800 */ 174,174,174,174,174,174,174,174,175,139,139,139,139,139,139,139, /* U+13000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+13800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+14000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+14800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+15000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+15800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+16000 */ 176,176,176,176,177,178,179,180,139,139,139,139,139,139,181,182, /* U+16800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+17000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+17800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+18000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+18800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+19000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+19800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1A800 */ 183,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1B000 */ 139,139,139,139,139,139,139,139,184,185,139,139,139,139,139,139, /* U+1B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1C800 */ 71,186,187,188,189,139,190,139,191,192,193,194,195,196,197,198, /* U+1D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1E000 */ 199,200,139,139,139,139,139,139,139,139,139,139,201,202,139,139, /* U+1E800 */ 203,204,205,206,207,139,208,209, 71,210,211,212,213,214,215,216, /* U+1F000 */ 217,218,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+1F800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+20000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+20800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+21000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+21800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+22000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+22800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+23000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+23800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+24000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+24800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+25000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+25800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+26000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+26800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+27000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+27800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+28000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+28800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+29000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+29800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95,219, 95, 95, /* U+2A000 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, /* U+2A800 */ 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95,220, 95, /* U+2B000 */ 221,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+2F000 */ 95, 95, 95, 95,221,139,139,139,139,139,139,139,139,139,139,139, /* U+2F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+30000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+30800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+31000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+31800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+32000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+32800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+33000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+33800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+34000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+34800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+35000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+35800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+36000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+36800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+37000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+37800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+38000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+38800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+39000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+39800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+3F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+40000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+40800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+41000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+41800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+42000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+42800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+43000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+43800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+44000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+44800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+45000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+45800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+46000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+46800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+47000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+47800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+48000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+48800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+49000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+49800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+4F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+50000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+50800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+51000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+51800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+52000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+52800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+53000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+53800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+54000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+54800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+55000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+55800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+56000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+56800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+57000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+57800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+58000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+58800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+59000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+59800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+5F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+60000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+60800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+61000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+61800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+62000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+62800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+63000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+63800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+64000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+64800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+65000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+65800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+66000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+66800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+67000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+67800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+68000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+68800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+69000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+69800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+6F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+70000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+70800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+71000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+71800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+72000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+72800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+73000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+73800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+74000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+74800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+75000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+75800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+76000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+76800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+77000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+77800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+78000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+78800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+79000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+79800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+7F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+80000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+80800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+81000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+81800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+82000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+82800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+83000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+83800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+84000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+84800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+85000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+85800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+86000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+86800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+87000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+87800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+88000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+88800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+89000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+89800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+8F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+90000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+90800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+91000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+91800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+92000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+92800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+93000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+93800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+94000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+94800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+95000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+95800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+96000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+96800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+97000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+97800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+98000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+98800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+99000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+99800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9A000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9A800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9B000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9B800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9C000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9C800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9D000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9D800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9E000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9E800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9F000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+9F800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A0000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A0800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A1000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A1800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A2000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A2800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A3000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A3800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A4000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A4800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A5000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A5800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A6000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A6800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A7000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A7800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A8000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A8800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A9000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+A9800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AA000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AA800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AB000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AB800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AC000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AC800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AD000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AD800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AE000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AE800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AF000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+AF800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B0000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B0800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B1000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B1800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B2000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B2800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B3000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B3800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B4000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B4800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B5000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B5800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B6000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B6800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B7000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B7800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B8000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B8800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B9000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+B9800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BA000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BA800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BB000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BB800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BC000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BC800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BD000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BD800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BE000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BE800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BF000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+BF800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C0000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C0800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C1000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C1800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C2000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C2800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C3000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C3800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C4000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C4800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C5000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C5800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C6000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C6800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C7000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C7800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C8000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C8800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C9000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+C9800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CA000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CA800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CB000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CB800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CC000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CC800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CD000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CD800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CE000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CE800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CF000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+CF800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D0000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D0800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D1000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D1800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D2000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D2800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D3000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D3800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D4000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D4800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D5000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D5800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D6000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D6800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D7000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D7800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D8000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D8800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D9000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+D9800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DA000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DA800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DB000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DB800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DC000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DC800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DD000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DD800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DE000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DE800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DF000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+DF800 */ 222,223,224,225,223,223,223,223,223,223,223,223,223,223,223,223, /* U+E0000 */ 223,223,223,223,223,223,223,223,223,223,223,223,223,223,223,223, /* U+E0800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E1000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E1800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E2000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E2800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E3000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E3800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E4000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E4800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E5000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E5800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E6000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E6800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E7000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E7800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E8000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E8800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E9000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+E9800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EA000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EA800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EB000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EB800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EC000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EC800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+ED000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+ED800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EE000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EE800 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EF000 */ 139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139, /* U+EF800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F0000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F0800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F1000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F1800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F2000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F2800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F3000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F3800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F4000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F4800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F5000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F5800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F6000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F6800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F7000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F7800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F8000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F8800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F9000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+F9800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FA000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FA800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FB000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FB800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FC000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FC800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FD000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FD800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FE000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FE800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+FF000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,226, /* U+FF800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+100000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+100800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+101000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+101800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+102000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+102800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+103000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+103800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+104000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+104800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+105000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+105800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+106000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+106800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+107000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+107800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+108000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+108800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+109000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+109800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10A000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10A800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10B000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10B800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10C000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10C800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10D000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10D800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10E000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10E800 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, /* U+10F000 */ 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,226, /* U+10F800 */ }; const pcre_uint16 PRIV(ucd_stage2)[] = { /* 58112 bytes, block = 128 */ /* block 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 4, 4, 5, 4, 4, 4, 6, 7, 4, 8, 4, 9, 4, 4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 8, 8, 8, 4, 4, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 11, 11, 11, 11, 11, 11, 11, 13, 11, 11, 11, 11, 11, 11, 11, 6, 4, 7, 14, 15, 14, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 16, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 16, 16, 16, 6, 8, 7, 8, 0, /* block 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 5, 5, 5, 5, 19, 4, 14, 19, 20, 21, 8, 22, 19, 14, 19, 8, 23, 23, 14, 24, 4, 4, 14, 23, 20, 25, 23, 23, 23, 4, 11, 11, 11, 11, 11, 26, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 8, 11, 11, 11, 11, 11, 11, 11, 27, 16, 16, 16, 16, 16, 28, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 8, 16, 16, 16, 16, 16, 16, 16, 29, /* block 2 */ 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 32, 33, 30, 31, 30, 31, 30, 31, 33, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 33, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 34, 30, 31, 30, 31, 30, 31, 35, /* block 3 */ 36, 37, 30, 31, 30, 31, 38, 30, 31, 39, 39, 30, 31, 33, 40, 41, 42, 30, 31, 39, 43, 44, 45, 46, 30, 31, 47, 33, 45, 48, 49, 50, 30, 31, 30, 31, 30, 31, 51, 30, 31, 51, 33, 33, 30, 31, 51, 30, 31, 52, 52, 30, 31, 30, 31, 53, 30, 31, 33, 20, 30, 31, 33, 54, 20, 20, 20, 20, 55, 56, 57, 58, 59, 60, 61, 62, 63, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 64, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 33, 65, 66, 67, 30, 31, 68, 69, 30, 31, 30, 31, 30, 31, 30, 31, /* block 4 */ 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 70, 33, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 33, 33, 33, 33, 33, 33, 71, 30, 31, 72, 73, 74, 74, 30, 31, 75, 76, 77, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 78, 79, 80, 81, 82, 33, 83, 83, 33, 84, 33, 85, 86, 33, 33, 33, 83, 87, 33, 88, 33, 89, 90, 33, 91, 92, 33, 93, 94, 33, 33, 92, 33, 95, 96, 33, 33, 97, 33, 33, 33, 33, 33, 33, 33, 98, 33, 33, /* block 5 */ 99, 33, 33, 99, 33, 33, 33,100, 99,101,102,102,103, 33, 33, 33, 33, 33,104, 33, 20, 33, 33, 33, 33, 33, 33, 33, 33, 33,105, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 106,106,106,106,106,106,106,106,106,107,107,107,107,107,107,107, 107,107, 14, 14, 14, 14,107,107,107,107,107,107,107,107,107,107, 107,107, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 106,106,106,106,106, 14, 14, 14, 14, 14,108,108,107, 14,107, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, /* block 6 */ 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,110,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 111,112,111,112,107,113,111,112,114,114,115,116,116,116, 4,117, /* block 7 */ 114,114,114,114,113, 14,118, 4,119,119,119,114,120,114,121,121, 122,123,124,123,123,125,123,123,126,127,128,123,129,123,123,123, 130,131,114,132,123,123,133,123,123,134,123,123,135,136,136,136, 122,137,138,137,137,139,137,137,140,141,142,137,143,137,137,137, 144,145,146,147,137,137,148,137,137,149,137,137,150,151,151,152, 153,154,155,155,155,156,157,158,111,112,111,112,111,112,111,112, 111,112,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 161,162,163,164,165,166,167,111,112,168,111,112,122,169,169,169, /* block 8 */ 170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170, 171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171, 171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171, 172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172, 172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172, 173,173,173,173,173,173,173,173,173,173,173,173,173,173,173,173, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, /* block 9 */ 174,175,176,177,177,109,109,177,178,178,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 179,174,175,174,175,174,175,174,175,174,175,174,175,174,175,180, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, /* block 10 */ 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 114,181,181,181,181,181,181,181,181,181,181,181,181,181,181,181, 181,181,181,181,181,181,181,181,181,181,181,181,181,181,181,181, 181,181,181,181,181,181,181,114,114,182,183,183,183,183,183,183, 114,184,184,184,184,184,184,184,184,184,184,184,184,184,184,184, 184,184,184,184,184,184,184,184,184,184,184,184,184,184,184,184, /* block 11 */ 184,184,184,184,184,184,184,185,114, 4,186,114,114,187,187,188, 114,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189, 189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189, 189,189,189,189,189,189,189,189,189,189,189,189,189,189,190,189, 191,189,189,191,189,189,191,189,114,114,114,114,114,114,114,114, 192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192, 192,192,192,192,192,192,192,192,192,192,192,114,114,114,114,114, 192,192,192,191,191,114,114,114,114,114,114,114,114,114,114,114, /* block 12 */ 193,193,193,193,193, 22,194,194,194,195,195,196, 4,195,197,197, 198,198,198,198,198,198,198,198,198,198,198, 4, 22,114,195, 4, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 107,199,199,199,199,199,199,199,199,199,199,109,109,109,109,109, 109,109,109,109,109,109,198,198,198,198,198,198,198,198,198,198, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,195,195,195,195,199,199, 109,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, /* block 13 */ 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,195,199,198,198,198,198,198,198,198, 22,197,198, 198,198,198,198,198,200,200,198,198,197,198,198,198,198,199,199, 201,201,201,201,201,201,201,201,201,201,199,199,199,197,197,199, /* block 14 */ 202,202,202,202,202,202,202,202,202,202,202,202,202,202,114,203, 204,205,204,204,204,204,204,204,204,204,204,204,204,204,204,204, 204,204,204,204,204,204,204,204,204,204,204,204,204,204,204,204, 205,205,205,205,205,205,205,205,205,205,205,205,205,205,205,205, 205,205,205,205,205,205,205,205,205,205,205,114,114,204,204,204, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, /* block 15 */ 206,206,206,206,206,206,206,206,206,206,206,206,206,206,206,206, 206,206,206,206,206,206,206,206,206,206,206,206,206,206,206,206, 206,206,206,206,206,206,207,207,207,207,207,207,207,207,207,207, 207,206,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 208,208,208,208,208,208,208,208,208,208,209,209,209,209,209,209, 209,209,209,209,209,209,209,209,209,209,209,209,209,209,209,209, 209,209,209,209,209,209,209,209,209,209,209,210,210,210,210,210, 210,210,210,210,211,211,212,213,213,213,211,114,114,114,114,114, /* block 16 */ 214,214,214,214,214,214,214,214,214,214,214,214,214,214,214,214, 214,214,214,214,214,214,215,215,215,215,216,215,215,215,215,215, 215,215,215,215,216,215,215,215,216,215,215,215,215,215,114,114, 217,217,217,217,217,217,217,217,217,217,217,217,217,217,217,114, 218,218,218,218,218,218,218,218,218,218,218,218,218,218,218,218, 218,218,218,218,218,218,218,218,218,219,219,219,114,114,220,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 17 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,198,198,198,198,198,198,198,198,198,198,198,198, 198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198, /* block 18 */ 221,221,221,222,223,223,223,223,223,223,223,223,223,223,223,223, 223,223,223,223,223,223,223,223,223,223,223,223,223,223,223,223, 223,223,223,223,223,223,223,223,223,223,223,223,223,223,223,223, 223,223,223,223,223,223,223,223,223,223,221,222,221,223,222,222, 222,221,221,221,221,221,221,221,221,222,222,222,222,221,222,222, 223,109,109,221,221,221,221,221,223,223,223,223,223,223,223,223, 223,223,221,221, 4, 4,224,224,224,224,224,224,224,224,224,224, 225,226,223,223,223,223,223,223,223,223,223,223,223,223,223,223, /* block 19 */ 227,228,229,229,114,227,227,227,227,227,227,227,227,114,114,227, 227,114,114,227,227,227,227,227,227,227,227,227,227,227,227,227, 227,227,227,227,227,227,227,227,227,114,227,227,227,227,227,227, 227,114,227,114,114,114,227,227,227,227,114,114,228,227,230,229, 229,228,228,228,228,114,114,229,229,114,114,229,229,228,227,114, 114,114,114,114,114,114,114,230,114,114,114,114,227,227,114,227, 227,227,228,228,114,114,231,231,231,231,231,231,231,231,231,231, 227,227,232,232,233,233,233,233,233,233,234,232,114,114,114,114, /* block 20 */ 114,235,235,236,114,237,237,237,237,237,237,114,114,114,114,237, 237,114,114,237,237,237,237,237,237,237,237,237,237,237,237,237, 237,237,237,237,237,237,237,237,237,114,237,237,237,237,237,237, 237,114,237,237,114,237,237,114,237,237,114,114,235,114,236,236, 236,235,235,114,114,114,114,235,235,114,114,235,235,235,114,114, 114,235,114,114,114,114,114,114,114,237,237,237,237,114,237,114, 114,114,114,114,114,114,238,238,238,238,238,238,238,238,238,238, 235,235,237,237,237,235,114,114,114,114,114,114,114,114,114,114, /* block 21 */ 114,239,239,240,114,241,241,241,241,241,241,241,241,241,114,241, 241,241,114,241,241,241,241,241,241,241,241,241,241,241,241,241, 241,241,241,241,241,241,241,241,241,114,241,241,241,241,241,241, 241,114,241,241,114,241,241,241,241,241,114,114,239,241,240,240, 240,239,239,239,239,239,114,239,239,240,114,240,240,239,114,114, 241,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 241,241,239,239,114,114,242,242,242,242,242,242,242,242,242,242, 243,244,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 22 */ 114,245,246,246,114,247,247,247,247,247,247,247,247,114,114,247, 247,114,114,247,247,247,247,247,247,247,247,247,247,247,247,247, 247,247,247,247,247,247,247,247,247,114,247,247,247,247,247,247, 247,114,247,247,114,247,247,247,247,247,114,114,245,247,248,245, 246,245,245,245,245,114,114,246,246,114,114,246,246,245,114,114, 114,114,114,114,114,114,245,248,114,114,114,114,247,247,114,247, 247,247,245,245,114,114,249,249,249,249,249,249,249,249,249,249, 250,247,251,251,251,251,251,251,114,114,114,114,114,114,114,114, /* block 23 */ 114,114,252,253,114,253,253,253,253,253,253,114,114,114,253,253, 253,114,253,253,253,253,114,114,114,253,253,114,253,114,253,253, 114,114,114,253,253,114,114,114,253,253,253,114,114,114,253,253, 253,253,253,253,253,253,253,253,253,253,114,114,114,114,254,255, 252,255,255,114,114,114,255,255,255,114,255,255,255,252,114,114, 253,114,114,114,114,114,114,254,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,256,256,256,256,256,256,256,256,256,256, 257,257,257,258,258,258,258,258,258,259,258,114,114,114,114,114, /* block 24 */ 260,261,261,261,114,262,262,262,262,262,262,262,262,114,262,262, 262,114,262,262,262,262,262,262,262,262,262,262,262,262,262,262, 262,262,262,262,262,262,262,262,262,114,262,262,262,262,262,262, 262,262,262,262,262,262,262,262,262,262,114,114,114,262,260,260, 260,261,261,261,261,114,260,260,260,114,260,260,260,260,114,114, 114,114,114,114,114,260,260,114,262,262,114,114,114,114,114,114, 262,262,260,260,114,114,263,263,263,263,263,263,263,263,263,263, 114,114,114,114,114,114,114,114,264,264,264,264,264,264,264,265, /* block 25 */ 114,266,267,267,114,268,268,268,268,268,268,268,268,114,268,268, 268,114,268,268,268,268,268,268,268,268,268,268,268,268,268,268, 268,268,268,268,268,268,268,268,268,114,268,268,268,268,268,268, 268,268,268,268,114,268,268,268,268,268,114,114,266,268,267,266, 267,267,269,267,267,114,266,267,267,114,267,267,266,266,114,114, 114,114,114,114,114,269,269,114,114,114,114,114,114,114,268,114, 268,268,266,266,114,114,270,270,270,270,270,270,270,270,270,270, 114,268,268,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 26 */ 114,271,272,272,114,273,273,273,273,273,273,273,273,114,273,273, 273,114,273,273,273,273,273,273,273,273,273,273,273,273,273,273, 273,273,273,273,273,273,273,273,273,273,273,273,273,273,273,273, 273,273,273,273,273,273,273,273,273,273,273,114,114,273,274,272, 272,271,271,271,271,114,272,272,272,114,272,272,272,271,273,114, 114,114,114,114,114,114,114,274,114,114,114,114,114,114,114,114, 273,273,271,271,114,114,275,275,275,275,275,275,275,275,275,275, 276,276,276,276,276,276,114,114,114,277,273,273,273,273,273,273, /* block 27 */ 114,114,278,278,114,279,279,279,279,279,279,279,279,279,279,279, 279,279,279,279,279,279,279,114,114,114,279,279,279,279,279,279, 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279, 279,279,114,279,279,279,279,279,279,279,279,279,114,279,114,114, 279,279,279,279,279,279,279,114,114,114,280,114,114,114,114,281, 278,278,280,280,280,114,280,114,278,278,278,278,278,278,278,281, 114,114,114,114,114,114,282,282,282,282,282,282,282,282,282,282, 114,114,278,278,283,114,114,114,114,114,114,114,114,114,114,114, /* block 28 */ 114,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284, 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284, 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284, 284,285,284,286,285,285,285,285,285,285,285,114,114,114,114, 5, 284,284,284,284,284,284,287,285,285,285,285,285,285,285,285,288, 289,289,289,289,289,289,289,289,289,289,288,288,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 29 */ 114,290,290,114,290,114,114,290,290,114,290,114,114,290,114,114, 114,114,114,114,290,290,290,290,114,290,290,290,290,290,290,290, 114,290,290,290,114,290,114,290,114,114,290,290,114,290,290,290, 290,291,290,292,291,291,291,291,291,291,114,291,291,290,114,114, 290,290,290,290,290,114,293,114,291,291,291,291,291,291,114,114, 294,294,294,294,294,294,294,294,294,294,114,114,290,290,290,290, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 30 */ 295,296,296,296,297,297,297,297,297,297,297,297,297,297,297,297, 297,297,297,296,297,296,296,296,298,298,296,296,296,296,296,296, 299,299,299,299,299,299,299,299,299,299,300,300,300,300,300,300, 300,300,300,300,296,298,296,298,296,298,301,302,301,302,303,303, 295,295,295,295,295,295,295,295,114,295,295,295,295,295,295,295, 295,295,295,295,295,295,295,295,295,295,295,295,295,295,295,295, 295,295,295,295,295,295,295,295,295,295,295,295,295,114,114,114, 114,298,298,298,298,298,298,298,298,298,298,298,298,298,298,303, /* block 31 */ 298,298,298,298,298,297,298,298,295,295,295,295,295,298,298,298, 298,298,298,298,298,298,298,298,114,298,298,298,298,298,298,298, 298,298,298,298,298,298,298,298,298,298,298,298,298,298,298,298, 298,298,298,298,298,298,298,298,298,298,298,298,298,114,296,296, 296,296,296,296,296,296,298,296,296,296,296,296,296,114,296,296, 297,297,297,297,297, 19, 19, 19, 19,297,297,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 32 */ 304,304,304,304,304,304,304,304,304,304,304,304,304,304,304,304, 304,304,304,304,304,304,304,304,304,304,304,304,304,304,304,304, 304,304,304,304,304,304,304,304,304,304,304,305,305,306,306,306, 306,307,306,306,306,306,306,306,305,306,306,307,307,306,306,304, 308,308,308,308,308,308,308,308,308,308,309,309,309,309,309,309, 304,304,304,304,304,304,307,307,306,306,304,304,304,304,306,306, 306,304,305,305,305,304,304,305,305,305,305,305,305,305,304,304, 304,306,306,306,306,304,304,304,304,304,304,304,304,304,304,304, /* block 33 */ 304,304,306,305,307,306,306,305,305,305,305,305,305,306,304,305, 308,308,308,308,308,308,308,308,308,308,305,305,305,306,310,310, 311,311,311,311,311,311,311,311,311,311,311,311,311,311,311,311, 311,311,311,311,311,311,311,311,311,311,311,311,311,311,311,311, 311,311,311,311,311,311,114,311,114,114,114,114,114,311,114,114, 312,312,312,312,312,312,312,312,312,312,312,312,312,312,312,312, 312,312,312,312,312,312,312,312,312,312,312,312,312,312,312,312, 312,312,312,312,312,312,312,312,312,312,312, 4,313,312,312,312, /* block 34 */ 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315, 315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315, /* block 35 */ 315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315, 315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315, 315,315,315,315,315,315,315,315,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, /* block 36 */ 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,114,317,317,317,317,114,114, 317,317,317,317,317,317,317,114,317,114,317,317,317,317,114,114, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, /* block 37 */ 317,317,317,317,317,317,317,317,317,114,317,317,317,317,114,114, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,114,317,317,317,317,114,114,317,317,317,317,317,317,317,114, 317,114,317,317,317,317,114,114,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,114,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, /* block 38 */ 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,114,317,317,317,317,114,114,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,317,317,317,317,114,114,318,318,318, 319,319,319,319,319,319,319,319,319,320,320,320,320,320,320,320, 320,320,320,320,320,320,320,320,320,320,320,320,320,114,114,114, /* block 39 */ 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 321,321,321,321,321,321,321,321,321,321,114,114,114,114,114,114, 322,322,322,322,322,322,322,322,322,322,322,322,322,322,322,322, 322,322,322,322,322,322,322,322,322,322,322,322,322,322,322,322, 322,322,322,322,322,322,322,322,322,322,322,322,322,322,322,322, 322,322,322,322,322,322,322,322,322,322,322,322,322,322,322,322, 322,322,322,322,322,322,322,322,322,322,322,322,322,322,322,322, 322,322,322,322,322,114,114,114,114,114,114,114,114,114,114,114, /* block 40 */ 323,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, /* block 41 */ 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, /* block 42 */ 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,325,325,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, /* block 43 */ 326,327,327,327,327,327,327,327,327,327,327,327,327,327,327,327, 327,327,327,327,327,327,327,327,327,327,327,328,329,114,114,114, 330,330,330,330,330,330,330,330,330,330,330,330,330,330,330,330, 330,330,330,330,330,330,330,330,330,330,330,330,330,330,330,330, 330,330,330,330,330,330,330,330,330,330,330,330,330,330,330,330, 330,330,330,330,330,330,330,330,330,330,330,330,330,330,330,330, 330,330,330,330,330,330,330,330,330,330,330, 4, 4, 4,331,331, 331,330,330,330,330,330,330,330,330,114,114,114,114,114,114,114, /* block 44 */ 332,332,332,332,332,332,332,332,332,332,332,332,332,114,332,332, 332,332,333,333,333,114,114,114,114,114,114,114,114,114,114,114, 334,334,334,334,334,334,334,334,334,334,334,334,334,334,334,334, 334,334,335,335,335, 4, 4,114,114,114,114,114,114,114,114,114, 336,336,336,336,336,336,336,336,336,336,336,336,336,336,336,336, 336,336,337,337,114,114,114,114,114,114,114,114,114,114,114,114, 338,338,338,338,338,338,338,338,338,338,338,338,338,114,338,338, 338,114,339,339,114,114,114,114,114,114,114,114,114,114,114,114, /* block 45 */ 340,340,340,340,340,340,340,340,340,340,340,340,340,340,340,340, 340,340,340,340,340,340,340,340,340,340,340,340,340,340,340,340, 340,340,340,340,340,340,340,340,340,340,340,340,340,340,340,340, 340,340,340,340,341,341,342,341,341,341,341,341,341,341,342,342, 342,342,342,342,342,342,341,342,342,341,341,341,341,341,341,341, 341,341,341,341,343,343,343,344,343,343,343,345,340,341,114,114, 346,346,346,346,346,346,346,346,346,346,114,114,114,114,114,114, 347,347,347,347,347,347,347,347,347,347,114,114,114,114,114,114, /* block 46 */ 348,348, 4, 4,348, 4,349,348,348,348,348,350,350,350,351,114, 352,352,352,352,352,352,352,352,352,352,114,114,114,114,114,114, 353,353,353,353,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,353,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,354,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,353,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,353,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,353,353,353,353,353,114,114,114,114,114,114,114,114, /* block 47 */ 353,353,353,353,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,353,353,353,353,353,353,353,353,353,353,353,353,353, 353,353,353,353,353,353,353,353,353,350,353,114,114,114,114,114, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,324,324,324,324,324,324,324,324,324,324, 324,324,324,324,324,324,114,114,114,114,114,114,114,114,114,114, /* block 48 */ 355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,355, 355,355,355,355,355,355,355,355,355,355,355,355,355,355,355,114, 356,356,356,357,357,357,357,356,356,357,357,357,114,114,114,114, 357,357,356,357,357,357,357,357,357,356,356,356,114,114,114,114, 358,114,114,114,359,359,360,360,360,360,360,360,360,360,360,360, 361,361,361,361,361,361,361,361,361,361,361,361,361,361,361,361, 361,361,361,361,361,361,361,361,361,361,361,361,361,361,114,114, 361,361,361,361,361,114,114,114,114,114,114,114,114,114,114,114, /* block 49 */ 362,362,362,362,362,362,362,362,362,362,362,362,362,362,362,362, 362,362,362,362,362,362,362,362,362,362,362,362,362,362,362,362, 362,362,362,362,362,362,362,362,362,362,362,362,114,114,114,114, 363,363,363,363,363,364,364,364,363,363,364,363,363,363,363,363, 363,362,362,362,362,362,362,362,363,363,114,114,114,114,114,114, 365,365,365,365,365,365,365,365,365,365,366,114,114,114,367,367, 368,368,368,368,368,368,368,368,368,368,368,368,368,368,368,368, 368,368,368,368,368,368,368,368,368,368,368,368,368,368,368,368, /* block 50 */ 369,369,369,369,369,369,369,369,369,369,369,369,369,369,369,369, 369,369,369,369,369,369,369,370,370,371,371,370,114,114,372,372, 373,373,373,373,373,373,373,373,373,373,373,373,373,373,373,373, 373,373,373,373,373,373,373,373,373,373,373,373,373,373,373,373, 373,373,373,373,373,373,373,373,373,373,373,373,373,373,373,373, 373,373,373,373,373,374,375,374,375,375,375,375,375,375,375,114, 375,376,375,376,376,375,375,375,375,375,375,375,375,374,374,374, 374,374,374,375,375,375,375,375,375,375,375,375,375,114,114,375, /* block 51 */ 377,377,377,377,377,377,377,377,377,377,114,114,114,114,114,114, 377,377,377,377,377,377,377,377,377,377,114,114,114,114,114,114, 378,378,378,378,378,378,378,379,378,378,378,378,378,378,114,114, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,380,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 52 */ 381,381,381,381,382,383,383,383,383,383,383,383,383,383,383,383, 383,383,383,383,383,383,383,383,383,383,383,383,383,383,383,383, 383,383,383,383,383,383,383,383,383,383,383,383,383,383,383,383, 383,383,383,383,381,382,381,381,381,381,381,382,381,382,382,382, 382,382,381,382,382,383,383,383,383,383,383,383,114,114,114,114, 384,384,384,384,384,384,384,384,384,384,385,385,385,385,385,385, 385,386,386,386,386,386,386,386,386,386,386,381,381,381,381,381, 381,381,381,381,386,386,386,386,386,386,386,386,386,114,114,114, /* block 53 */ 387,387,388,389,389,389,389,389,389,389,389,389,389,389,389,389, 389,389,389,389,389,389,389,389,389,389,389,389,389,389,389,389, 389,388,387,387,387,387,388,388,387,387,388,387,387,387,389,389, 390,390,390,390,390,390,390,390,390,390,389,389,389,389,389,389, 391,391,391,391,391,391,391,391,391,391,391,391,391,391,391,391, 391,391,391,391,391,391,391,391,391,391,391,391,391,391,391,391, 391,391,391,391,391,391,392,393,392,392,393,393,393,392,393,392, 392,392,393,393,114,114,114,114,114,114,114,114,394,394,394,394, /* block 54 */ 395,395,395,395,395,395,395,395,395,395,395,395,395,395,395,395, 395,395,395,395,395,395,395,395,395,395,395,395,395,395,395,395, 395,395,395,395,396,396,396,396,396,396,396,396,397,397,397,397, 397,397,397,397,396,396,397,397,114,114,114,398,398,398,398,398, 399,399,399,399,399,399,399,399,399,399,114,114,114,395,395,395, 400,400,400,400,400,400,400,400,400,400,401,401,401,401,401,401, 401,401,401,401,401,401,401,401,401,401,401,401,401,401,401,401, 401,401,401,401,401,401,401,401,402,402,402,402,402,402,403,403, /* block 55 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 404,404,404,404,404,404,404,404,114,114,114,114,114,114,114,114, 109,109,109, 4,109,109,109,109,109,109,109,109,109,109,109,109, 109,405,109,109,109,109,109,109,109,406,406,406,406,109,406,406, 406,406,405,405,109,406,406,114,109,109,114,114,114,114,114,114, /* block 56 */ 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,122,122,122,122,122,407,106,106,106,106, 106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106, 106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106, 106,106,106,106,106,106,106,106,106,106,106,106,106,115,115,115, 115,115,106,106,106,106,115,115,115,115,115, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,408,409, 33, 33, 33,410, 33, 33, /* block 57 */ 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,106,106,106,106,106, 106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,106, 106,106,106,106,106,106,106,106,106,106,106,106,106,106,106,115, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,114,114,114,114,114,114,109,109,109,109, /* block 58 */ 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 411,412, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, /* block 59 */ 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 33, 33, 33, 33, 33,413, 33, 33,414, 33, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, /* block 60 */ 415,415,415,415,415,415,415,415,416,416,416,416,416,416,416,416, 415,415,415,415,415,415,114,114,416,416,416,416,416,416,114,114, 415,415,415,415,415,415,415,415,416,416,416,416,416,416,416,416, 415,415,415,415,415,415,415,415,416,416,416,416,416,416,416,416, 415,415,415,415,415,415,114,114,416,416,416,416,416,416,114,114, 122,415,122,415,122,415,122,415,114,416,114,416,114,416,114,416, 415,415,415,415,415,415,415,415,416,416,416,416,416,416,416,416, 417,417,418,418,418,418,419,419,420,420,421,421,422,422,114,114, /* block 61 */ 415,415,415,415,415,415,415,415,423,423,423,423,423,423,423,423, 415,415,415,415,415,415,415,415,423,423,423,423,423,423,423,423, 415,415,415,415,415,415,415,415,423,423,423,423,423,423,423,423, 415,415,122,424,122,114,122,122,416,416,425,425,426,113,427,113, 113,113,122,424,122,114,122,122,428,428,428,428,426,113,113,113, 415,415,122,122,114,114,122,122,416,416,429,429,114,113,113,113, 415,415,122,122,122,163,122,122,416,416,430,430,168,113,113,113, 114,114,122,424,122,114,122,122,431,431,432,432,426,113,113,114, /* block 62 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 22,433,433, 22, 22, 9, 9, 9, 9, 9, 9, 4, 4, 21, 25, 6, 21, 21, 25, 6, 21, 4, 4, 4, 4, 4, 4, 4, 4,434,435, 22, 22, 22, 22, 22, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 21, 25, 4, 4, 4, 4, 15, 15, 4, 4, 4, 8, 6, 7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 4, 15, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 22, 22, 22, 22, 22,436, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,106,114,114, 23, 23, 23, 23, 23, 23, 8, 8, 8, 6, 7,106, /* block 63 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 8, 8, 8, 6, 7,114, 106,106,106,106,106,106,106,106,106,106,106,106,106,114,114,114, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 109,109,109,109,109,109,109,109,109,109,109,109,109,380,380,380, 380,109,380,380,380,109,109,109,109,109,109,109,109,109,109,109, 109,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 64 */ 19, 19,437, 19, 19, 19, 19,437, 19, 19,438,437,437,437,438,438, 437,437,437,438, 19,437, 19, 19, 8,437,437,437,437,437, 19, 19, 19, 19, 19, 19,437, 19,439, 19,437, 19,440,441,437,437, 19,438, 437,437,442,437,438,406,406,406,406,438, 19, 19,438,438,437,437, 8, 8, 8, 8, 8,437,438,438,438,438, 19, 8, 19, 19,443, 19, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 444,444,444,444,444,444,444,444,444,444,444,444,444,444,444,444, 445,445,445,445,445,445,445,445,445,445,445,445,445,445,445,445, /* block 65 */ 446,446,446, 30, 31,446,446,446,446, 23,114,114,114,114,114,114, 8, 8, 8, 8, 8, 19, 19, 19, 19, 19, 8, 8, 19, 19, 19, 19, 8, 19, 19, 8, 19, 19, 8, 19, 19, 19, 19, 19, 19, 19, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 19, 19, 8, 19, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, /* block 66 */ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, /* block 67 */ 19, 19, 19, 19, 19, 19, 19, 19, 6, 7, 6, 7, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 19, 19, 19, 19, 19, 19, 19, 6, 7, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 19, 19, 19, /* block 68 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 8, 8, 8, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114, /* block 69 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, /* block 70 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,447,447,447,447,447,447,447,447,447,447, 447,447,447,447,447,447,447,447,447,447,447,447,447,447,447,447, 448,448,448,448,448,448,448,448,448,448,448,448,448,448,448,448, 448,448,448,448,448,448,448,448,448,448, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, /* block 71 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 72 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 8, 8, 8, 8, 8, 8, /* block 73 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 74 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, /* block 75 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 8, 8, 8, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, /* block 76 */ 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, 449,449,449,449,449,449,449,449,449,449,449,449,449,449,449,449, /* block 77 */ 8, 8, 8, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 7, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 7, 8, 8, /* block 78 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 19, 19, 8, 8, 8, 8, 8, 8, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 79 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 80 */ 450,450,450,450,450,450,450,450,450,450,450,450,450,450,450,450, 450,450,450,450,450,450,450,450,450,450,450,450,450,450,450,450, 450,450,450,450,450,450,450,450,450,450,450,450,450,450,450,114, 451,451,451,451,451,451,451,451,451,451,451,451,451,451,451,451, 451,451,451,451,451,451,451,451,451,451,451,451,451,451,451,451, 451,451,451,451,451,451,451,451,451,451,451,451,451,451,451,114, 30, 31,452,453,454,455,456, 30, 31, 30, 31, 30, 31,457,458,459, 460, 33, 30, 31, 33, 30, 31, 33, 33, 33, 33, 33,106,106,461,461, /* block 81 */ 159,160,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 159,160,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 159,160,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 159,160,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 159,160,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 159,160,159,160,159,160,159,160,159,160,159,160,159,160,159,160, 159,160,159,160,462,463,463,463,463,463,463,159,160,159,160,464, 464,464,159,160,114,114,114,114,114,465,465,465,465,466,465,465, /* block 82 */ 467,467,467,467,467,467,467,467,467,467,467,467,467,467,467,467, 467,467,467,467,467,467,467,467,467,467,467,467,467,467,467,467, 467,467,467,467,467,467,114,467,114,114,114,114,114,467,114,114, 468,468,468,468,468,468,468,468,468,468,468,468,468,468,468,468, 468,468,468,468,468,468,468,468,468,468,468,468,468,468,468,468, 468,468,468,468,468,468,468,468,468,468,468,468,468,468,468,468, 468,468,468,468,468,468,468,468,114,114,114,114,114,114,114,469, 470,114,114,114,114,114,114,114,114,114,114,114,114,114,114,471, /* block 83 */ 317,317,317,317,317,317,317,317,317,317,317,317,317,317,317,317, 317,317,317,317,317,317,317,114,114,114,114,114,114,114,114,114, 317,317,317,317,317,317,317,114,317,317,317,317,317,317,317,114, 317,317,317,317,317,317,317,114,317,317,317,317,317,317,317,114, 317,317,317,317,317,317,317,114,317,317,317,317,317,317,317,114, 317,317,317,317,317,317,317,114,317,317,317,317,317,317,317,114, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, 177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177, /* block 84 */ 4, 4, 21, 25, 21, 25, 4, 4, 4, 21, 25, 4, 21, 25, 4, 4, 4, 4, 4, 4, 4, 4, 4, 9, 4, 4, 9, 4, 21, 25, 4, 4, 21, 25, 6, 7, 6, 7, 6, 7, 6, 7, 4, 4, 4, 4, 4,107, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 9, 9, 4, 4, 4, 4, 9, 4, 6,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 85 */ 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,114,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,114,114,114,114,114,114,114,114,114,114,114,114, /* block 86 */ 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, /* block 87 */ 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,472,472,472,472,472,472,472,472,472,472, 472,472,472,472,472,472,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114, /* block 88 */ 3, 4, 4, 4, 19,473,406,474, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 19, 19, 6, 7, 6, 7, 6, 7, 6, 7, 9, 6, 7, 7, 19,474,474,474,474,474,474,474,474,474,109,109,109,109,475,475, 9,107,107,107,107,107, 19, 19,474,474,474,473,406, 4, 19, 19, 114,476,476,476,476,476,476,476,476,476,476,476,476,476,476,476, 476,476,476,476,476,476,476,476,476,476,476,476,476,476,476,476, 476,476,476,476,476,476,476,476,476,476,476,476,476,476,476,476, 476,476,476,476,476,476,476,476,476,476,476,476,476,476,476,476, /* block 89 */ 476,476,476,476,476,476,476,476,476,476,476,476,476,476,476,476, 476,476,476,476,476,476,476,114,114,109,109, 14, 14,477,477,476, 9,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, 478,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, 478,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, 478,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, 478,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, 478,478,478,478,478,478,478,478,478,478,478, 4,107,479,479,478, /* block 90 */ 114,114,114,114,114,480,480,480,480,480,480,480,480,480,480,480, 480,480,480,480,480,480,480,480,480,480,480,480,480,480,480,480, 480,480,480,480,480,480,480,480,480,480,480,480,480,480,114,114, 114,481,481,481,481,481,481,481,481,481,481,481,481,481,481,481, 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,481, 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,481, 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,481, 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,481, /* block 91 */ 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,114, 19, 19, 23, 23, 23, 23, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 480,480,480,480,480,480,480,480,480,480,480,480,480,480,480,480, 480,480,480,480,480,480,480,480,480,480,480,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114, 478,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, /* block 92 */ 482,482,482,482,482,482,482,482,482,482,482,482,482,482,482,482, 482,482,482,482,482,482,482,482,482,482,482,482,482,482,482,114, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 23, 23, 23, 23, 23, 23, 23, 23, 19, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 482,482,482,482,482,482,482,482,482,482,482,482,482,482,482,482, 482,482,482,482,482,482,482,482,482,482,482,482,482,482,482, 19, /* block 93 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,114, /* block 94 */ 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483,483,483,483,483,483,483,483,483, 483,483,483,483,483,483,483,483, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 95 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, /* block 96 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 97 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 98 */ 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,486,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, /* block 99 */ 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, 485,485,485,485,485,485,485,485,485,485,485,485,485,485,485,485, /* block 100 */ 485,485,485,485,485,485,485,485,485,485,485,485,485,114,114,114, 487,487,487,487,487,487,487,487,487,487,487,487,487,487,487,487, 487,487,487,487,487,487,487,487,487,487,487,487,487,487,487,487, 487,487,487,487,487,487,487,487,487,487,487,487,487,487,487,487, 487,487,487,487,487,487,487,114,114,114,114,114,114,114,114,114, 488,488,488,488,488,488,488,488,488,488,488,488,488,488,488,488, 488,488,488,488,488,488,488,488,488,488,488,488,488,488,488,488, 488,488,488,488,488,488,488,488,489,489,489,489,489,489,490,490, /* block 101 */ 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, /* block 102 */ 491,491,491,491,491,491,491,491,491,491,491,491,492,493,493,493, 491,491,491,491,491,491,491,491,491,491,491,491,491,491,491,491, 494,494,494,494,494,494,494,494,494,494,491,491,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,174,175,495,177, 178,178,178,496,177,177,177,177,177,177,177,177,177,177,496,408, /* block 103 */ 174,175,174,175,174,175,174,175,174,175,174,175,174,175,174,175, 174,175,174,175,174,175,174,175,174,175,174,175,408,408,114,177, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,498,498,498,498,498,498,498,498,498,498, 499,499,500,500,500,500,500,500,114,114,114,114,114,114,114,114, /* block 104 */ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,107,107,107,107,107,107,107,107,107, 14, 14, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 33, 33, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 106, 33, 33, 33, 33, 33, 33, 33, 33, 30, 31, 30, 31,501, 30, 31, /* block 105 */ 30, 31, 30, 31, 30, 31, 30, 31,107, 14, 14, 30, 31,502, 33,114, 30, 31, 30, 31, 33, 33, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31,503,504,505,506,114,114, 507,508,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114, 20,106,106, 33, 20, 20, 20, 20, 20, /* block 106 */ 509,509,510,509,509,509,510,509,509,509,509,510,509,509,509,509, 509,509,509,509,509,509,509,509,509,509,509,509,509,509,509,509, 509,509,509,511,511,510,510,511,512,512,512,512,114,114,114,114, 23, 23, 23, 23, 23, 23, 19, 19, 5, 19,114,114,114,114,114,114, 513,513,513,513,513,513,513,513,513,513,513,513,513,513,513,513, 513,513,513,513,513,513,513,513,513,513,513,513,513,513,513,513, 513,513,513,513,513,513,513,513,513,513,513,513,513,513,513,513, 513,513,513,513,514,514,514,514,114,114,114,114,114,114,114,114, /* block 107 */ 515,515,516,516,516,516,516,516,516,516,516,516,516,516,516,516, 516,516,516,516,516,516,516,516,516,516,516,516,516,516,516,516, 516,516,516,516,516,516,516,516,516,516,516,516,516,516,516,516, 516,516,516,516,515,515,515,515,515,515,515,515,515,515,515,515, 515,515,515,515,517,114,114,114,114,114,114,114,114,114,518,518, 519,519,519,519,519,519,519,519,519,519,114,114,114,114,114,114, 221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221, 221,221,223,223,223,223,223,223,225,225,225,223,114,114,114,114, /* block 108 */ 520,520,520,520,520,520,520,520,520,520,521,521,521,521,521,521, 521,521,521,521,521,521,521,521,521,521,521,521,521,521,521,521, 521,521,521,521,521,521,522,522,522,522,522,522,522,522, 4,523, 524,524,524,524,524,524,524,524,524,524,524,524,524,524,524,524, 524,524,524,524,524,524,524,525,525,525,525,525,525,525,525,525, 525,525,526,526,114,114,114,114,114,114,114,114,114,114,114,527, 314,314,314,314,314,314,314,314,314,314,314,314,314,314,314,314, 314,314,314,314,314,314,314,314,314,314,314,314,314,114,114,114, /* block 109 */ 528,528,528,529,530,530,530,530,530,530,530,530,530,530,530,530, 530,530,530,530,530,530,530,530,530,530,530,530,530,530,530,530, 530,530,530,530,530,530,530,530,530,530,530,530,530,530,530,530, 530,530,530,528,529,529,528,528,528,528,529,529,528,529,529,529, 529,531,531,531,531,531,531,531,531,531,531,531,531,531,114,107, 532,532,532,532,532,532,532,532,532,532,114,114,114,114,531,531, 304,304,304,304,304,306,533,304,304,304,304,304,304,304,304,304, 308,308,308,308,308,308,308,308,308,308,304,304,304,304,304,114, /* block 110 */ 534,534,534,534,534,534,534,534,534,534,534,534,534,534,534,534, 534,534,534,534,534,534,534,534,534,534,534,534,534,534,534,534, 534,534,534,534,534,534,534,534,534,535,535,535,535,535,535,536, 536,535,535,536,536,535,535,114,114,114,114,114,114,114,114,114, 534,534,534,535,534,534,534,534,534,534,534,534,535,536,114,114, 537,537,537,537,537,537,537,537,537,537,114,114,538,538,538,538, 304,304,304,304,304,304,304,304,304,304,304,304,304,304,304,304, 533,304,304,304,304,304,304,310,310,310,304,305,306,305,304,304, /* block 111 */ 539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539, 539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539, 539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539, 540,539,540,540,540,539,539,540,540,539,539,539,539,539,540,540, 539,540,539,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,539,539,541,542,542, 543,543,543,543,543,543,543,543,543,543,543,544,545,545,544,544, 546,546,543,547,547,544,545,114,114,114,114,114,114,114,114,114, /* block 112 */ 114,317,317,317,317,317,317,114,114,317,317,317,317,317,317,114, 114,317,317,317,317,317,317,114,114,114,114,114,114,114,114,114, 317,317,317,317,317,317,317,114,317,317,317,317,317,317,317,114, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 14,106,106,106,106, 114,114,114,114, 33,122,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 113 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 543,543,543,543,543,543,543,543,543,543,543,543,543,543,543,543, 543,543,543,543,543,543,543,543,543,543,543,543,543,543,543,543, 543,543,543,544,544,545,544,544,545,544,544,546,544,545,114,114, 548,548,548,548,548,548,548,548,548,548,114,114,114,114,114,114, /* block 114 */ 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, /* block 115 */ 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, /* block 116 */ 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, /* block 117 */ 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, /* block 118 */ 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, /* block 119 */ 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, /* block 120 */ 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 549,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,549,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,549,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, /* block 121 */ 550,550,550,550,550,550,550,550,549,550,550,550,550,550,550,550, 550,550,550,550,550,550,550,550,550,550,550,550,550,550,550,550, 550,550,550,550,114,114,114,114,114,114,114,114,114,114,114,114, 315,315,315,315,315,315,315,315,315,315,315,315,315,315,315,315, 315,315,315,315,315,315,315,114,114,114,114,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,316,316,316,316, 316,316,316,316,316,316,316,316,316,316,316,316,114,114,114,114, /* block 122 */ 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, 551,551,551,551,551,551,551,551,551,551,551,551,551,551,551,551, /* block 123 */ 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, /* block 124 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,114,114, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, /* block 125 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 126 */ 33, 33, 33, 33, 33, 33, 33,114,114,114,114,114,114,114,114,114, 114,114,114,185,185,185,185,185,114,114,114,114,114,192,189,192, 192,192,192,192,192,192,192,192,192,553,192,192,192,192,192,192, 192,192,192,192,192,192,192,114,192,192,192,192,192,114,192,114, 192,192,114,192,192,114,192,192,192,192,192,192,192,192,192,192, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, /* block 127 */ 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,554,554,554,554,554,554,554,554,554,554,554,554,554,554, 554,554,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, /* block 128 */ 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, /* block 129 */ 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199, 7, 6, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, /* block 130 */ 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 114,114,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 199,199,199,199,199,199,199,199,199,199,199,199,196,197,114,114, /* block 131 */ 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 4, 4, 4, 4, 4, 4, 4, 6, 7, 4,114,114,114,114,114,114, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,114,114, 4, 9, 9, 15, 15, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 4, 4, 6, 7, 4, 4, 4, 4, 15, 15, 15, 4, 4, 4,114, 4, 4, 4, 4, 9, 6, 7, 6, 7, 6, 7, 4, 4, 4, 8, 9, 8, 8, 8,114, 4, 5, 4, 4,114,114,114,114, 199,199,199,199,199,114,199,199,199,199,199,199,199,199,199,199, /* block 132 */ 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,114,114, 22, /* block 133 */ 114, 4, 4, 4, 5, 4, 4, 4, 6, 7, 4, 8, 4, 9, 4, 4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 8, 8, 8, 4, 4, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, 4, 7, 14, 15, 14, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 6, 8, 7, 8, 6, 7, 4, 6, 7, 4, 4,478,478,478,478,478,478,478,478,478,478, 107,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, /* block 134 */ 478,478,478,478,478,478,478,478,478,478,478,478,478,478,478,478, 478,478,478,478,478,478,478,478,478,478,478,478,478,478,555,555, 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,481, 481,481,481,481,481,481,481,481,481,481,481,481,481,481,481,114, 114,114,481,481,481,481,481,481,114,114,481,481,481,481,481,481, 114,114,481,481,481,481,481,481,114,114,481,481,481,114,114,114, 5, 5, 8, 14, 19, 5, 5,114, 19, 8, 8, 8, 8, 19, 19,114, 436,436,436,436,436,436,436,436,436, 22, 22, 22, 19, 19,114,114, /* block 135 */ 556,556,556,556,556,556,556,556,556,556,556,556,114,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,114,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,114,556,556,114,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,114,114, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 136 */ 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,556,556,556,556,556, 556,556,556,556,556,556,556,556,556,556,556,114,114,114,114,114, /* block 137 */ 4, 4, 4,114,114,114,114, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 557,557,557,557,557,557,557,557,557,557,557,557,557,557,557,557, 557,557,557,557,557,557,557,557,557,557,557,557,557,557,557,557, 557,557,557,557,557,557,557,557,557,557,557,557,557,557,557,557, 557,557,557,557,557,558,558,558,558,559,559,559,559,559,559,559, /* block 138 */ 559,559,559,559,559,559,559,559,559,559,558,558,559,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114, 559,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,109,114,114, /* block 139 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 140 */ 560,560,560,560,560,560,560,560,560,560,560,560,560,560,560,560, 560,560,560,560,560,560,560,560,560,560,560,560,560,114,114,114, 561,561,561,561,561,561,561,561,561,561,561,561,561,561,561,561, 561,561,561,561,561,561,561,561,561,561,561,561,561,561,561,561, 561,561,561,561,561,561,561,561,561,561,561,561,561,561,561,561, 561,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 109, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,114,114,114,114, /* block 141 */ 562,562,562,562,562,562,562,562,562,562,562,562,562,562,562,562, 562,562,562,562,562,562,562,562,562,562,562,562,562,562,562,562, 563,563,563,563,114,114,114,114,114,114,114,114,114,114,114,114, 564,564,564,564,564,564,564,564,564,564,564,564,564,564,564,564, 564,565,564,564,564,564,564,564,564,564,565,114,114,114,114,114, 566,566,566,566,566,566,566,566,566,566,566,566,566,566,566,566, 566,566,566,566,566,566,566,566,566,566,566,566,566,566,566,566, 566,566,566,566,566,566,567,567,567,567,567,114,114,114,114,114, /* block 142 */ 568,568,568,568,568,568,568,568,568,568,568,568,568,568,568,568, 568,568,568,568,568,568,568,568,568,568,568,568,568,568,114,569, 570,570,570,570,570,570,570,570,570,570,570,570,570,570,570,570, 570,570,570,570,570,570,570,570,570,570,570,570,570,570,570,570, 570,570,570,570,114,114,114,114,570,570,570,570,570,570,570,570, 571,572,572,572,572,572,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 143 */ 573,573,573,573,573,573,573,573,573,573,573,573,573,573,573,573, 573,573,573,573,573,573,573,573,573,573,573,573,573,573,573,573, 573,573,573,573,573,573,573,573,574,574,574,574,574,574,574,574, 574,574,574,574,574,574,574,574,574,574,574,574,574,574,574,574, 574,574,574,574,574,574,574,574,574,574,574,574,574,574,574,574, 575,575,575,575,575,575,575,575,575,575,575,575,575,575,575,575, 575,575,575,575,575,575,575,575,575,575,575,575,575,575,575,575, 575,575,575,575,575,575,575,575,575,575,575,575,575,575,575,575, /* block 144 */ 576,576,576,576,576,576,576,576,576,576,576,576,576,576,576,576, 576,576,576,576,576,576,576,576,576,576,576,576,576,576,114,114, 577,577,577,577,577,577,577,577,577,577,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 145 */ 578,578,578,578,578,578,578,578,578,578,578,578,578,578,578,578, 578,578,578,578,578,578,578,578,578,578,578,578,578,578,578,578, 578,578,578,578,578,578,578,578,114,114,114,114,114,114,114,114, 579,579,579,579,579,579,579,579,579,579,579,579,579,579,579,579, 579,579,579,579,579,579,579,579,579,579,579,579,579,579,579,579, 579,579,579,579,579,579,579,579,579,579,579,579,579,579,579,579, 579,579,579,579,114,114,114,114,114,114,114,114,114,114,114,580, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 146 */ 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, /* block 147 */ 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,581,114,114,114,114,114,114,114,114,114, 581,581,581,581,581,581,581,581,581,581,581,581,581,581,581,581, 581,581,581,581,581,581,114,114,114,114,114,114,114,114,114,114, 581,581,581,581,581,581,581,581,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 148 */ 582,582,582,582,582,582,114,114,582,114,582,582,582,582,582,582, 582,582,582,582,582,582,582,582,582,582,582,582,582,582,582,582, 582,582,582,582,582,582,582,582,582,582,582,582,582,582,582,582, 582,582,582,582,582,582,114,582,582,114,114,114,582,114,114,582, 583,583,583,583,583,583,583,583,583,583,583,583,583,583,583,583, 583,583,583,583,583,583,114,584,585,585,585,585,585,585,585,585, 586,586,586,586,586,586,586,586,586,586,586,586,586,586,586,586, 586,586,586,586,586,586,586,587,587,588,588,588,588,588,588,588, /* block 149 */ 589,589,589,589,589,589,589,589,589,589,589,589,589,589,589,589, 589,589,589,589,589,589,589,589,589,589,589,589,589,589,589,114, 114,114,114,114,114,114,114,590,590,590,590,590,590,590,590,590, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 150 */ 591,591,591,591,591,591,591,591,591,591,591,591,591,591,591,591, 591,591,591,591,591,591,592,592,592,592,592,592,114,114,114,593, 594,594,594,594,594,594,594,594,594,594,594,594,594,594,594,594, 594,594,594,594,594,594,594,594,594,594,114,114,114,114,114,595, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 151 */ 596,596,596,596,596,596,596,596,596,596,596,596,596,596,596,596, 596,596,596,596,596,596,596,596,596,596,596,596,596,596,596,596, 597,597,597,597,597,597,597,597,597,597,597,597,597,597,597,597, 597,597,597,597,597,597,597,597,114,114,114,114,114,114,597,597, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 152 */ 598,599,599,599,114,599,599,114,114,114,114,114,599,599,599,599, 598,598,598,598,114,598,598,598,114,598,598,598,598,598,598,598, 598,598,598,598,598,598,598,598,598,598,598,598,598,598,598,598, 598,598,598,598,114,114,114,114,599,599,599,114,114,114,114,599, 600,600,600,600,600,600,600,600,114,114,114,114,114,114,114,114, 601,601,601,601,601,601,601,601,601,114,114,114,114,114,114,114, 602,602,602,602,602,602,602,602,602,602,602,602,602,602,602,602, 602,602,602,602,602,602,602,602,602,602,602,602,602,603,603,604, /* block 153 */ 605,605,605,605,605,605,605,605,605,605,605,605,605,605,605,605, 605,605,605,605,605,605,605,605,605,605,605,605,605,606,606,606, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 607,607,607,607,607,607,607,607,608,607,607,607,607,607,607,607, 607,607,607,607,607,607,607,607,607,607,607,607,607,607,607,607, 607,607,607,607,607,609,609,114,114,114,114,610,610,610,610,610, 611,611,611,611,611,611,611,114,114,114,114,114,114,114,114,114, /* block 154 */ 612,612,612,612,612,612,612,612,612,612,612,612,612,612,612,612, 612,612,612,612,612,612,612,612,612,612,612,612,612,612,612,612, 612,612,612,612,612,612,612,612,612,612,612,612,612,612,612,612, 612,612,612,612,612,612,114,114,114,613,613,613,613,613,613,613, 614,614,614,614,614,614,614,614,614,614,614,614,614,614,614,614, 614,614,614,614,614,614,114,114,615,615,615,615,615,615,615,615, 616,616,616,616,616,616,616,616,616,616,616,616,616,616,616,616, 616,616,616,114,114,114,114,114,617,617,617,617,617,617,617,617, /* block 155 */ 618,618,618,618,618,618,618,618,618,618,618,618,618,618,618,618, 618,618,114,114,114,114,114,114,114,619,619,619,619,114,114,114, 114,114,114,114,114,114,114,114,114,620,620,620,620,620,620,620, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 156 */ 621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621, 621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621, 621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621, 621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621, 621,621,621,621,621,621,621,621,621,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 157 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622, 622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,114, /* block 158 */ 623,624,623,625,625,625,625,625,625,625,625,625,625,625,625,625, 625,625,625,625,625,625,625,625,625,625,625,625,625,625,625,625, 625,625,625,625,625,625,625,625,625,625,625,625,625,625,625,625, 625,625,625,625,625,625,625,625,624,624,624,624,624,624,624,624, 624,624,624,624,624,624,624,626,626,626,626,626,626,626,114,114, 114,114,627,627,627,627,627,627,627,627,627,627,627,627,627,627, 627,627,627,627,627,627,628,628,628,628,628,628,628,628,628,628, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,624, /* block 159 */ 629,629,630,631,631,631,631,631,631,631,631,631,631,631,631,631, 631,631,631,631,631,631,631,631,631,631,631,631,631,631,631,631, 631,631,631,631,631,631,631,631,631,631,631,631,631,631,631,631, 630,630,630,629,629,629,629,630,630,629,629,632,632,633,632,632, 632,632,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634, 634,634,634,634,634,634,634,634,634,114,114,114,114,114,114,114, 635,635,635,635,635,635,635,635,635,635,114,114,114,114,114,114, /* block 160 */ 636,636,636,637,637,637,637,637,637,637,637,637,637,637,637,637, 637,637,637,637,637,637,637,637,637,637,637,637,637,637,637,637, 637,637,637,637,637,637,637,636,636,636,636,636,638,636,636,636, 636,636,636,636,636,114,639,639,639,639,639,639,639,639,639,639, 640,640,640,640,114,114,114,114,114,114,114,114,114,114,114,114, 641,641,641,641,641,641,641,641,641,641,641,641,641,641,641,641, 641,641,641,641,641,641,641,641,641,641,641,641,641,641,641,641, 641,641,641,642,643,643,641,114,114,114,114,114,114,114,114,114, /* block 161 */ 644,644,645,646,646,646,646,646,646,646,646,646,646,646,646,646, 646,646,646,646,646,646,646,646,646,646,646,646,646,646,646,646, 646,646,646,646,646,646,646,646,646,646,646,646,646,646,646,646, 646,646,646,645,645,645,644,644,644,644,644,644,644,644,644,645, 645,646,646,646,646,647,647,647,647,114,114,114,114,647,114,114, 648,648,648,648,648,648,648,648,648,648,646,114,114,114,114,114, 114,649,649,649,649,649,649,649,649,649,649,649,649,649,649,649, 649,649,649,649,649,114,114,114,114,114,114,114,114,114,114,114, /* block 162 */ 650,650,650,650,650,650,650,650,650,650,650,650,650,650,650,650, 650,650,114,650,650,650,650,650,650,650,650,650,650,650,650,650, 650,650,650,650,650,650,650,650,650,650,650,650,651,651,651,652, 652,652,651,651,652,651,652,652,653,653,653,653,653,653,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 163 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 654,654,654,654,654,654,654,654,654,654,654,654,654,654,654,654, 654,654,654,654,654,654,654,654,654,654,654,654,654,654,654,654, 654,654,654,654,654,654,654,654,654,654,654,654,654,654,654,655, 656,656,656,655,655,655,655,655,655,655,655,114,114,114,114,114, 657,657,657,657,657,657,657,657,657,657,114,114,114,114,114,114, /* block 164 */ 114,658,659,659,114,660,660,660,660,660,660,660,660,114,114,660, 660,114,114,660,660,660,660,660,660,660,660,660,660,660,660,660, 660,660,660,660,660,660,660,660,660,114,660,660,660,660,660,660, 660,114,660,660,114,660,660,660,660,660,114,114,658,660,661,659, 658,659,659,659,659,114,114,659,659,114,114,659,659,659,114,114, 114,114,114,114,114,114,114,661,114,114,114,114,114,660,660,660, 660,660,659,659,114,114,658,658,658,658,658,658,658,114,114,114, 658,658,658,658,658,114,114,114,114,114,114,114,114,114,114,114, /* block 165 */ 662,662,662,662,662,662,662,662,662,662,662,662,662,662,662,662, 662,662,662,662,662,662,662,662,662,662,662,662,662,662,662,662, 662,662,662,662,662,662,662,662,662,662,662,662,662,662,662,662, 663,664,664,665,665,665,665,665,665,664,665,664,664,663,664,665, 665,664,665,665,662,662,666,662,114,114,114,114,114,114,114,114, 667,667,667,667,667,667,667,667,667,667,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 166 */ 668,668,668,668,668,668,668,668,668,668,668,668,668,668,668,668, 668,668,668,668,668,668,668,668,668,668,668,668,668,668,668,668, 668,668,668,668,668,668,668,668,668,668,668,668,668,668,668,669, 670,670,671,671,671,671,114,114,670,670,670,670,671,671,670,671, 671,672,672,672,672,672,672,672,672,672,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 167 */ 673,673,673,673,673,673,673,673,673,673,673,673,673,673,673,673, 673,673,673,673,673,673,673,673,673,673,673,673,673,673,673,673, 673,673,673,673,673,673,673,673,673,673,673,673,673,673,673,673, 674,674,674,675,675,675,675,675,675,675,675,674,674,675,674,675, 675,676,676,676,673,114,114,114,114,114,114,114,114,114,114,114, 677,677,677,677,677,677,677,677,677,677,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 168 */ 678,678,678,678,678,678,678,678,678,678,678,678,678,678,678,678, 678,678,678,678,678,678,678,678,678,678,678,678,678,678,678,678, 678,678,678,678,678,678,678,678,678,678,678,679,680,679,680,680, 679,679,679,679,679,679,680,679,114,114,114,114,114,114,114,114, 681,681,681,681,681,681,681,681,681,681,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 169 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 682,682,682,682,682,682,682,682,682,682,682,682,682,682,682,682, 682,682,682,682,682,682,682,682,682,682,682,682,682,682,682,682, 683,683,683,683,683,683,683,683,683,683,683,683,683,683,683,683, 683,683,683,683,683,683,683,683,683,683,683,683,683,683,683,683, 684,684,684,684,684,684,684,684,684,684,685,685,685,685,685,685, 685,685,685,114,114,114,114,114,114,114,114,114,114,114,114,686, /* block 170 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 687,687,687,687,687,687,687,687,687,687,687,687,687,687,687,687, 687,687,687,687,687,687,687,687,687,687,687,687,687,687,687,687, 687,687,687,687,687,687,687,687,687,687,687,687,687,687,687,687, 687,687,687,687,687,687,687,687,687,114,114,114,114,114,114,114, /* block 171 */ 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, /* block 172 */ 688,688,688,688,688,688,688,688,688,688,688,688,688,688,688,688, 688,688,688,688,688,688,688,688,688,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 173 */ 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,689, 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,689, 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,689, 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,689, 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,689, 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,689, 689,689,689,689,689,689,689,689,689,689,689,689,689,689,689,114, 690,690,690,690,690,114,114,114,114,114,114,114,114,114,114,114, /* block 174 */ 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, /* block 175 */ 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,691, 691,691,691,691,691,691,691,691,691,691,691,691,691,691,691,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 176 */ 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, /* block 177 */ 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,497,497,497,497,497,497,497, 497,497,497,497,497,497,497,497,497,114,114,114,114,114,114,114, 692,692,692,692,692,692,692,692,692,692,692,692,692,692,692,692, 692,692,692,692,692,692,692,692,692,692,692,692,692,692,692,114, 693,693,693,693,693,693,693,693,693,693,114,114,114,114,694,694, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 178 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 695,695,695,695,695,695,695,695,695,695,695,695,695,695,695,695, 695,695,695,695,695,695,695,695,695,695,695,695,695,695,114,114, 696,696,696,696,696,697,114,114,114,114,114,114,114,114,114,114, /* block 179 */ 698,698,698,698,698,698,698,698,698,698,698,698,698,698,698,698, 698,698,698,698,698,698,698,698,698,698,698,698,698,698,698,698, 698,698,698,698,698,698,698,698,698,698,698,698,698,698,698,698, 699,699,699,699,699,699,699,700,700,700,700,700,701,701,701,701, 702,702,702,702,700,701,114,114,114,114,114,114,114,114,114,114, 703,703,703,703,703,703,703,703,703,703,114,704,704,704,704,704, 704,704,114,698,698,698,698,698,698,698,698,698,698,698,698,698, 698,698,698,698,698,698,698,698,114,114,114,114,114,698,698,698, /* block 180 */ 698,698,698,698,698,698,698,698,698,698,698,698,698,698,698,698, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 181 */ 705,705,705,705,705,705,705,705,705,705,705,705,705,705,705,705, 705,705,705,705,705,705,705,705,705,705,705,705,705,705,705,705, 705,705,705,705,705,705,705,705,705,705,705,705,705,705,705,705, 705,705,705,705,705,705,705,705,705,705,705,705,705,705,705,705, 705,705,705,705,705,114,114,114,114,114,114,114,114,114,114,114, 705,706,706,706,706,706,706,706,706,706,706,706,706,706,706,706, 706,706,706,706,706,706,706,706,706,706,706,706,706,706,706,706, 706,706,706,706,706,706,706,706,706,706,706,706,706,706,706,114, /* block 182 */ 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,707, 707,707,707,708,708,708,708,708,708,708,708,708,708,708,708,708, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 183 */ 478,476,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 184 */ 709,709,709,709,709,709,709,709,709,709,709,709,709,709,709,709, 709,709,709,709,709,709,709,709,709,709,709,709,709,709,709,709, 709,709,709,709,709,709,709,709,709,709,709,709,709,709,709,709, 709,709,709,709,709,709,709,709,709,709,709,709,709,709,709,709, 709,709,709,709,709,709,709,709,709,709,709,709,709,709,709,709, 709,709,709,709,709,709,709,709,709,709,709,709,709,709,709,709, 709,709,709,709,709,709,709,709,709,709,709,114,114,114,114,114, 709,709,709,709,709,709,709,709,709,709,709,709,709,114,114,114, /* block 185 */ 709,709,709,709,709,709,709,709,709,114,114,114,114,114,114,114, 709,709,709,709,709,709,709,709,709,709,114,114,710,711,711,712, 22, 22, 22, 22,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 186 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114, /* block 187 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,713,405,109,109,109, 19, 19, 19,405,713,713, 713,713,713, 22, 22, 22, 22, 22, 22, 22, 22,109,109,109,109,109, /* block 188 */ 109,109,109, 19, 19,109,109,109,109,109,109,109, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,109,109,109,109, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 189 */ 559,559,559,559,559,559,559,559,559,559,559,559,559,559,559,559, 559,559,559,559,559,559,559,559,559,559,559,559,559,559,559,559, 559,559,559,559,559,559,559,559,559,559,559,559,559,559,559,559, 559,559,559,559,559,559,559,559,559,559,559,559,559,559,559,559, 559,559,714,714,714,559,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 190 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 191 */ 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,438,438, 438,438,438,438,438,114,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, /* block 192 */ 437,437,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,437,114,437,437, 114,114,437,114,114,437,437,114,114,437,437,437,437,114,437,437, 437,437,437,437,437,437,438,438,438,438,114,438,114,438,438,438, 438,438,438,438,114,438,438,438,438,438,438,438,438,438,438,438, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, /* block 193 */ 438,438,438,438,437,437,114,437,437,437,437,114,114,437,437,437, 437,437,437,437,437,114,437,437,437,437,437,437,437,114,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,437,437,114,437,437,437,437,114, 437,437,437,437,437,114,437,114,114,114,437,437,437,437,437,437, 437,114,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, /* block 194 */ 437,437,437,437,437,437,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, /* block 195 */ 438,438,438,438,438,438,438,438,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, /* block 196 */ 437,437,437,437,437,437,437,437,437,437,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,114,114,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437, 8,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438, 8,438,438,438,438, 438,438,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437, 8,438,438,438,438, /* block 197 */ 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438, 8,438,438,438,438,438,438,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437, 8,438,438,438,438,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 8, 438,438,438,438,438,438,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 8, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, /* block 198 */ 438,438,438,438,438,438,438,438,438, 8,438,438,438,438,438,438, 437,437,437,437,437,437,437,437,437,437,437,437,437,437,437,437, 437,437,437,437,437,437,437,437,437, 8,438,438,438,438,438,438, 438,438,438,438,438,438,438,438,438,438,438,438,438,438,438,438, 438,438,438, 8,438,438,438,438,438,438,437,438,114,114, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, /* block 199 */ 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, /* block 200 */ 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,715,715,715,715,715,715,715,715,715,715,715, 715,715,715,715,715,114,114,716,716,716,716,716,716,716,716,716, 717,717,717,717,717,717,717,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 201 */ 199,199,199,199,114,199,199,199,199,199,199,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199, 114,199,199,114,199,114,114,199,114,199,199,199,199,199,199,199, 199,199,199,114,199,199,199,199,114,199,114,199,114,114,114,114, 114,114,199,114,114,114,114,199,114,199,114,199,114,199,199,199, 114,199,199,114,199,114,114,199,114,199,114,199,114,199,114,199, 114,199,199,114,199,114,114,199,199,199,199,114,199,199,199,199, 199,199,199,114,199,199,199,199,114,199,199,199,199,114,199,114, /* block 202 */ 199,199,199,199,199,199,199,199,199,199,114,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,114,114,114,114, 114,199,199,199,114,199,199,199,199,199,114,199,199,199,199,199, 199,199,199,199,199,199,199,199,199,199,199,199,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 194,194,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 203 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 204 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, 114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114, /* block 205 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 206 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,718,718,718,718,718,718,718,718,718,718, 718,718,718,718,718,718,718,718,718,718,718,718,718,718,718,718, /* block 207 */ 719, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 208 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, /* block 209 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, 114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114, /* block 210 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, /* block 211 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, 19, 19, 19, 19, 19, /* block 212 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 213 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 214 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114, /* block 215 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114,114,114, /* block 216 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 217 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, /* block 218 */ 19, 19, 19, 19, 19, 19, 19, 19,114,114,114,114,114,114,114,114, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 219 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 220 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,114,114,114,114,114,114,114,114,114,114,114, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, /* block 221 */ 484,484,484,484,484,484,484,484,484,484,484,484,484,484,484,484, 484,484,484,484,484,484,484,484,484,484,484,484,484,484,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, 114,114,114,114,114,114,114,114,114,114,114,114,114,114,114,114, /* block 222 */ 436, 22,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, /* block 223 */ 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, /* block 224 */ 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, /* block 225 */ 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 109,109,109,109,109,109,109,109,109,109,109,109,109,109,109,109, 436,436,436,436,436,436,436,436,436,436,436,436,436,436,436,436, /* block 226 */ 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552, 552,552,552,552,552,552,552,552,552,552,552,552,552,552,114,114, }; #if UCD_BLOCK_SIZE != 128 #error Please correct UCD_BLOCK_SIZE in pcre_internal.h #endif #endif /* SUPPORT_UCP */ #endif /* PCRE_INCLUDED */
libgit2-main
deps/pcre/pcre_ucd.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2014 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This module contains an internal function that tests a compiled pattern to see if it was compiled with the opposite endianness. If so, it uses an auxiliary local function to flip the appropriate bytes. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre_internal.h" /************************************************* * Swap byte functions * *************************************************/ /* The following functions swap the bytes of a pcre_uint16 and pcre_uint32 value. Arguments: value any number Returns: the byte swapped value */ static pcre_uint32 swap_uint32(pcre_uint32 value) { return ((value & 0x000000ff) << 24) | ((value & 0x0000ff00) << 8) | ((value & 0x00ff0000) >> 8) | (value >> 24); } static pcre_uint16 swap_uint16(pcre_uint16 value) { return (value >> 8) | (value << 8); } /************************************************* * Test for a byte-flipped compiled regex * *************************************************/ /* This function swaps the bytes of a compiled pattern usually loaded form the disk. It also sets the tables pointer, which is likely an invalid pointer after reload. Arguments: argument_re points to the compiled expression extra_data points to extra data or is NULL tables points to the character tables or NULL Returns: 0 if the swap is successful, negative on error */ #if defined COMPILE_PCRE8 PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *argument_re, pcre_extra *extra_data, const unsigned char *tables) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *argument_re, pcre16_extra *extra_data, const unsigned char *tables) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *argument_re, pcre32_extra *extra_data, const unsigned char *tables) #endif { REAL_PCRE *re = (REAL_PCRE *)argument_re; pcre_study_data *study; #ifndef COMPILE_PCRE8 pcre_uchar *ptr; int length; #if defined SUPPORT_UTF && defined COMPILE_PCRE16 BOOL utf; BOOL utf16_char; #endif /* SUPPORT_UTF && COMPILE_PCRE16 */ #endif /* !COMPILE_PCRE8 */ if (re == NULL) return PCRE_ERROR_NULL; if (re->magic_number == MAGIC_NUMBER) { if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; re->tables = tables; return 0; } if (re->magic_number != REVERSED_MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; if ((swap_uint32(re->flags) & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; re->magic_number = MAGIC_NUMBER; re->size = swap_uint32(re->size); re->options = swap_uint32(re->options); re->flags = swap_uint32(re->flags); re->limit_match = swap_uint32(re->limit_match); re->limit_recursion = swap_uint32(re->limit_recursion); #if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 re->first_char = swap_uint16(re->first_char); re->req_char = swap_uint16(re->req_char); #elif defined COMPILE_PCRE32 re->first_char = swap_uint32(re->first_char); re->req_char = swap_uint32(re->req_char); #endif re->max_lookbehind = swap_uint16(re->max_lookbehind); re->top_bracket = swap_uint16(re->top_bracket); re->top_backref = swap_uint16(re->top_backref); re->name_table_offset = swap_uint16(re->name_table_offset); re->name_entry_size = swap_uint16(re->name_entry_size); re->name_count = swap_uint16(re->name_count); re->ref_count = swap_uint16(re->ref_count); re->tables = tables; if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) { study = (pcre_study_data *)extra_data->study_data; study->size = swap_uint32(study->size); study->flags = swap_uint32(study->flags); study->minlength = swap_uint32(study->minlength); } #ifndef COMPILE_PCRE8 ptr = (pcre_uchar *)re + re->name_table_offset; length = re->name_count * re->name_entry_size; #if defined SUPPORT_UTF && defined COMPILE_PCRE16 utf = (re->options & PCRE_UTF16) != 0; utf16_char = FALSE; #endif /* SUPPORT_UTF && COMPILE_PCRE16 */ while(TRUE) { /* Swap previous characters. */ while (length-- > 0) { #if defined COMPILE_PCRE16 *ptr = swap_uint16(*ptr); #elif defined COMPILE_PCRE32 *ptr = swap_uint32(*ptr); #endif ptr++; } #if defined SUPPORT_UTF && defined COMPILE_PCRE16 if (utf16_char) { if (HAS_EXTRALEN(ptr[-1])) { /* We know that there is only one extra character in UTF-16. */ *ptr = swap_uint16(*ptr); ptr++; } } utf16_char = FALSE; #endif /* SUPPORT_UTF */ /* Get next opcode. */ length = 0; #if defined COMPILE_PCRE16 *ptr = swap_uint16(*ptr); #elif defined COMPILE_PCRE32 *ptr = swap_uint32(*ptr); #endif switch (*ptr) { case OP_END: return 0; #if defined SUPPORT_UTF && defined COMPILE_PCRE16 case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_UPTOI: case OP_MINUPTOI: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: if (utf) utf16_char = TRUE; #endif /* Fall through. */ default: length = PRIV(OP_lengths)[*ptr] - 1; break; case OP_CLASS: case OP_NCLASS: /* Skip the character bit map. */ ptr += 32/sizeof(pcre_uchar); length = 0; break; case OP_XCLASS: /* Reverse the size of the XCLASS instance. */ ptr++; #if defined COMPILE_PCRE16 *ptr = swap_uint16(*ptr); #elif defined COMPILE_PCRE32 *ptr = swap_uint32(*ptr); #endif #ifndef COMPILE_PCRE32 if (LINK_SIZE > 1) { /* LINK_SIZE can be 1 or 2 in 16 bit mode. */ ptr++; *ptr = swap_uint16(*ptr); } #endif ptr++; length = (GET(ptr, -LINK_SIZE)) - (1 + LINK_SIZE + 1); #if defined COMPILE_PCRE16 *ptr = swap_uint16(*ptr); #elif defined COMPILE_PCRE32 *ptr = swap_uint32(*ptr); #endif if ((*ptr & XCL_MAP) != 0) { /* Skip the character bit map. */ ptr += 32/sizeof(pcre_uchar); length -= 32/sizeof(pcre_uchar); } break; } ptr++; } /* Control should never reach here in 16/32 bit mode. */ #else /* In 8-bit mode, the pattern does not need to be processed. */ return 0; #endif /* !COMPILE_PCRE8 */ } /* End of pcre_byte_order.c */
libgit2-main
deps/pcre/pcre_byte_order.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2013 University of Cambridge The machine code generator part (this module) was written by Zoltan Herczeg Copyright (c) 2010-2013 ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre_internal.h" #if defined SUPPORT_JIT /* All-in-one: Since we use the JIT compiler only from here, we just include it. This way we don't need to touch the build system files. */ #define SLJIT_MALLOC(size, allocator_data) (PUBL(malloc))(size) #define SLJIT_FREE(ptr, allocator_data) (PUBL(free))(ptr) #define SLJIT_CONFIG_AUTO 1 #define SLJIT_CONFIG_STATIC 1 #define SLJIT_VERBOSE 0 #define SLJIT_DEBUG 0 #include "sljit/sljitLir.c" #if defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED #error Unsupported architecture #endif /* Defines for debugging purposes. */ /* 1 - Use unoptimized capturing brackets. 2 - Enable capture_last_ptr (includes option 1). */ /* #define DEBUG_FORCE_UNOPTIMIZED_CBRAS 2 */ /* 1 - Always have a control head. */ /* #define DEBUG_FORCE_CONTROL_HEAD 1 */ /* Allocate memory for the regex stack on the real machine stack. Fast, but limited size. */ #define MACHINE_STACK_SIZE 32768 /* Growth rate for stack allocated by the OS. Should be the multiply of page size. */ #define STACK_GROWTH_RATE 8192 /* Enable to check that the allocation could destroy temporaries. */ #if defined SLJIT_DEBUG && SLJIT_DEBUG #define DESTROY_REGISTERS 1 #endif /* Short summary about the backtracking mechanism empolyed by the jit code generator: The code generator follows the recursive nature of the PERL compatible regular expressions. The basic blocks of regular expressions are condition checkers whose execute different commands depending on the result of the condition check. The relationship between the operators can be horizontal (concatenation) and vertical (sub-expression) (See struct backtrack_common for more details). 'ab' - 'a' and 'b' regexps are concatenated 'a+' - 'a' is the sub-expression of the '+' operator The condition checkers are boolean (true/false) checkers. Machine code is generated for the checker itself and for the actions depending on the result of the checker. The 'true' case is called as the matching path (expected path), and the other is called as the 'backtrack' path. Branch instructions are expesive for all CPUs, so we avoid taken branches on the matching path. Greedy star operator (*) : Matching path: match happens. Backtrack path: match failed. Non-greedy star operator (*?) : Matching path: no need to perform a match. Backtrack path: match is required. The following example shows how the code generated for a capturing bracket with two alternatives. Let A, B, C, D are arbirary regular expressions, and we have the following regular expression: A(B|C)D The generated code will be the following: A matching path '(' matching path (pushing arguments to the stack) B matching path ')' matching path (pushing arguments to the stack) D matching path return with successful match D backtrack path ')' backtrack path (If we arrived from "C" jump to the backtrack of "C") B backtrack path C expected path jump to D matching path C backtrack path A backtrack path Notice, that the order of backtrack code paths are the opposite of the fast code paths. In this way the topmost value on the stack is always belong to the current backtrack code path. The backtrack path must check whether there is a next alternative. If so, it needs to jump back to the matching path eventually. Otherwise it needs to clear out its own stack frame and continue the execution on the backtrack code paths. */ /* Saved stack frames: Atomic blocks and asserts require reloading the values of private data when the backtrack mechanism performed. Because of OP_RECURSE, the data are not necessarly known in compile time, thus we need a dynamic restore mechanism. The stack frames are stored in a chain list, and have the following format: ([ capturing bracket offset ][ start value ][ end value ])+ ... [ 0 ] [ previous head ] Thus we can restore the private data to a particular point in the stack. */ typedef struct jit_arguments { /* Pointers first. */ struct sljit_stack *stack; const pcre_uchar *str; const pcre_uchar *begin; const pcre_uchar *end; int *offsets; pcre_uchar *mark_ptr; void *callout_data; /* Everything else after. */ sljit_u32 limit_match; int real_offset_count; int offset_count; sljit_u8 notbol; sljit_u8 noteol; sljit_u8 notempty; sljit_u8 notempty_atstart; } jit_arguments; typedef struct executable_functions { void *executable_funcs[JIT_NUMBER_OF_COMPILE_MODES]; void *read_only_data_heads[JIT_NUMBER_OF_COMPILE_MODES]; sljit_uw executable_sizes[JIT_NUMBER_OF_COMPILE_MODES]; PUBL(jit_callback) callback; void *userdata; sljit_u32 top_bracket; sljit_u32 limit_match; } executable_functions; typedef struct jump_list { struct sljit_jump *jump; struct jump_list *next; } jump_list; typedef struct stub_list { struct sljit_jump *start; struct sljit_label *quit; struct stub_list *next; } stub_list; typedef struct label_addr_list { struct sljit_label *label; sljit_uw *update_addr; struct label_addr_list *next; } label_addr_list; enum frame_types { no_frame = -1, no_stack = -2 }; enum control_types { type_mark = 0, type_then_trap = 1 }; typedef int (SLJIT_FUNC *jit_function)(jit_arguments *args); /* The following structure is the key data type for the recursive code generator. It is allocated by compile_matchingpath, and contains the arguments for compile_backtrackingpath. Must be the first member of its descendants. */ typedef struct backtrack_common { /* Concatenation stack. */ struct backtrack_common *prev; jump_list *nextbacktracks; /* Internal stack (for component operators). */ struct backtrack_common *top; jump_list *topbacktracks; /* Opcode pointer. */ pcre_uchar *cc; } backtrack_common; typedef struct assert_backtrack { backtrack_common common; jump_list *condfailed; /* Less than 0 if a frame is not needed. */ int framesize; /* Points to our private memory word on the stack. */ int private_data_ptr; /* For iterators. */ struct sljit_label *matchingpath; } assert_backtrack; typedef struct bracket_backtrack { backtrack_common common; /* Where to coninue if an alternative is successfully matched. */ struct sljit_label *alternative_matchingpath; /* For rmin and rmax iterators. */ struct sljit_label *recursive_matchingpath; /* For greedy ? operator. */ struct sljit_label *zero_matchingpath; /* Contains the branches of a failed condition. */ union { /* Both for OP_COND, OP_SCOND. */ jump_list *condfailed; assert_backtrack *assert; /* For OP_ONCE. Less than 0 if not needed. */ int framesize; } u; /* Points to our private memory word on the stack. */ int private_data_ptr; } bracket_backtrack; typedef struct bracketpos_backtrack { backtrack_common common; /* Points to our private memory word on the stack. */ int private_data_ptr; /* Reverting stack is needed. */ int framesize; /* Allocated stack size. */ int stacksize; } bracketpos_backtrack; typedef struct braminzero_backtrack { backtrack_common common; struct sljit_label *matchingpath; } braminzero_backtrack; typedef struct char_iterator_backtrack { backtrack_common common; /* Next iteration. */ struct sljit_label *matchingpath; union { jump_list *backtracks; struct { unsigned int othercasebit; pcre_uchar chr; BOOL enabled; } charpos; } u; } char_iterator_backtrack; typedef struct ref_iterator_backtrack { backtrack_common common; /* Next iteration. */ struct sljit_label *matchingpath; } ref_iterator_backtrack; typedef struct recurse_entry { struct recurse_entry *next; /* Contains the function entry. */ struct sljit_label *entry; /* Collects the calls until the function is not created. */ jump_list *calls; /* Points to the starting opcode. */ sljit_sw start; } recurse_entry; typedef struct recurse_backtrack { backtrack_common common; BOOL inlined_pattern; } recurse_backtrack; #define OP_THEN_TRAP OP_TABLE_LENGTH typedef struct then_trap_backtrack { backtrack_common common; /* If then_trap is not NULL, this structure contains the real then_trap for the backtracking path. */ struct then_trap_backtrack *then_trap; /* Points to the starting opcode. */ sljit_sw start; /* Exit point for the then opcodes of this alternative. */ jump_list *quit; /* Frame size of the current alternative. */ int framesize; } then_trap_backtrack; #define MAX_RANGE_SIZE 4 typedef struct compiler_common { /* The sljit ceneric compiler. */ struct sljit_compiler *compiler; /* First byte code. */ pcre_uchar *start; /* Maps private data offset to each opcode. */ sljit_s32 *private_data_ptrs; /* Chain list of read-only data ptrs. */ void *read_only_data_head; /* Tells whether the capturing bracket is optimized. */ sljit_u8 *optimized_cbracket; /* Tells whether the starting offset is a target of then. */ sljit_u8 *then_offsets; /* Current position where a THEN must jump. */ then_trap_backtrack *then_trap; /* Starting offset of private data for capturing brackets. */ sljit_s32 cbra_ptr; /* Output vector starting point. Must be divisible by 2. */ sljit_s32 ovector_start; /* Points to the starting character of the current match. */ sljit_s32 start_ptr; /* Last known position of the requested byte. */ sljit_s32 req_char_ptr; /* Head of the last recursion. */ sljit_s32 recursive_head_ptr; /* First inspected character for partial matching. (Needed for avoiding zero length partial matches.) */ sljit_s32 start_used_ptr; /* Starting pointer for partial soft matches. */ sljit_s32 hit_start; /* Pointer of the match end position. */ sljit_s32 match_end_ptr; /* Points to the marked string. */ sljit_s32 mark_ptr; /* Recursive control verb management chain. */ sljit_s32 control_head_ptr; /* Points to the last matched capture block index. */ sljit_s32 capture_last_ptr; /* Fast forward skipping byte code pointer. */ pcre_uchar *fast_forward_bc_ptr; /* Locals used by fast fail optimization. */ sljit_s32 fast_fail_start_ptr; sljit_s32 fast_fail_end_ptr; /* Flipped and lower case tables. */ const sljit_u8 *fcc; sljit_sw lcc; /* Mode can be PCRE_STUDY_JIT_COMPILE and others. */ int mode; /* TRUE, when minlength is greater than 0. */ BOOL might_be_empty; /* \K is found in the pattern. */ BOOL has_set_som; /* (*SKIP:arg) is found in the pattern. */ BOOL has_skip_arg; /* (*THEN) is found in the pattern. */ BOOL has_then; /* (*SKIP) or (*SKIP:arg) is found in lookbehind assertion. */ BOOL has_skip_in_assert_back; /* Currently in recurse or negative assert. */ BOOL local_exit; /* Currently in a positive assert. */ BOOL positive_assert; /* Newline control. */ int nltype; sljit_u32 nlmax; sljit_u32 nlmin; int newline; int bsr_nltype; sljit_u32 bsr_nlmax; sljit_u32 bsr_nlmin; /* Dollar endonly. */ int endonly; /* Tables. */ sljit_sw ctypes; /* Named capturing brackets. */ pcre_uchar *name_table; sljit_sw name_count; sljit_sw name_entry_size; /* Labels and jump lists. */ struct sljit_label *partialmatchlabel; struct sljit_label *quit_label; struct sljit_label *forced_quit_label; struct sljit_label *accept_label; struct sljit_label *ff_newline_shortcut; stub_list *stubs; label_addr_list *label_addrs; recurse_entry *entries; recurse_entry *currententry; jump_list *partialmatch; jump_list *quit; jump_list *positive_assert_quit; jump_list *forced_quit; jump_list *accept; jump_list *calllimit; jump_list *stackalloc; jump_list *revertframes; jump_list *wordboundary; jump_list *anynewline; jump_list *hspace; jump_list *vspace; jump_list *casefulcmp; jump_list *caselesscmp; jump_list *reset_match; BOOL jscript_compat; #ifdef SUPPORT_UTF BOOL utf; #ifdef SUPPORT_UCP BOOL use_ucp; jump_list *getucd; #endif #ifdef COMPILE_PCRE8 jump_list *utfreadchar; jump_list *utfreadchar16; jump_list *utfreadtype8; #endif #endif /* SUPPORT_UTF */ } compiler_common; /* For byte_sequence_compare. */ typedef struct compare_context { int length; int sourcereg; #if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED int ucharptr; union { sljit_s32 asint; sljit_u16 asushort; #if defined COMPILE_PCRE8 sljit_u8 asbyte; sljit_u8 asuchars[4]; #elif defined COMPILE_PCRE16 sljit_u16 asuchars[2]; #elif defined COMPILE_PCRE32 sljit_u32 asuchars[1]; #endif } c; union { sljit_s32 asint; sljit_u16 asushort; #if defined COMPILE_PCRE8 sljit_u8 asbyte; sljit_u8 asuchars[4]; #elif defined COMPILE_PCRE16 sljit_u16 asuchars[2]; #elif defined COMPILE_PCRE32 sljit_u32 asuchars[1]; #endif } oc; #endif } compare_context; /* Undefine sljit macros. */ #undef CMP /* Used for accessing the elements of the stack. */ #define STACK(i) ((i) * (int)sizeof(sljit_sw)) #ifdef SLJIT_PREF_SHIFT_REG #if SLJIT_PREF_SHIFT_REG == SLJIT_R2 /* Nothing. */ #elif SLJIT_PREF_SHIFT_REG == SLJIT_R3 #define SHIFT_REG_IS_R3 #else #error "Unsupported shift register" #endif #endif #define TMP1 SLJIT_R0 #ifdef SHIFT_REG_IS_R3 #define TMP2 SLJIT_R3 #define TMP3 SLJIT_R2 #else #define TMP2 SLJIT_R2 #define TMP3 SLJIT_R3 #endif #define STR_PTR SLJIT_S0 #define STR_END SLJIT_S1 #define STACK_TOP SLJIT_R1 #define STACK_LIMIT SLJIT_S2 #define COUNT_MATCH SLJIT_S3 #define ARGUMENTS SLJIT_S4 #define RETURN_ADDR SLJIT_R4 /* Local space layout. */ /* These two locals can be used by the current opcode. */ #define LOCALS0 (0 * sizeof(sljit_sw)) #define LOCALS1 (1 * sizeof(sljit_sw)) /* Two local variables for possessive quantifiers (char1 cannot use them). */ #define POSSESSIVE0 (2 * sizeof(sljit_sw)) #define POSSESSIVE1 (3 * sizeof(sljit_sw)) /* Max limit of recursions. */ #define LIMIT_MATCH (4 * sizeof(sljit_sw)) /* The output vector is stored on the stack, and contains pointers to characters. The vector data is divided into two groups: the first group contains the start / end character pointers, and the second is the start pointers when the end of the capturing group has not yet reached. */ #define OVECTOR_START (common->ovector_start) #define OVECTOR(i) (OVECTOR_START + (i) * (sljit_sw)sizeof(sljit_sw)) #define OVECTOR_PRIV(i) (common->cbra_ptr + (i) * (sljit_sw)sizeof(sljit_sw)) #define PRIVATE_DATA(cc) (common->private_data_ptrs[(cc) - common->start]) #if defined COMPILE_PCRE8 #define MOV_UCHAR SLJIT_MOV_U8 #elif defined COMPILE_PCRE16 #define MOV_UCHAR SLJIT_MOV_U16 #elif defined COMPILE_PCRE32 #define MOV_UCHAR SLJIT_MOV_U32 #else #error Unsupported compiling mode #endif /* Shortcuts. */ #define DEFINE_COMPILER \ struct sljit_compiler *compiler = common->compiler #define OP1(op, dst, dstw, src, srcw) \ sljit_emit_op1(compiler, (op), (dst), (dstw), (src), (srcw)) #define OP2(op, dst, dstw, src1, src1w, src2, src2w) \ sljit_emit_op2(compiler, (op), (dst), (dstw), (src1), (src1w), (src2), (src2w)) #define LABEL() \ sljit_emit_label(compiler) #define JUMP(type) \ sljit_emit_jump(compiler, (type)) #define JUMPTO(type, label) \ sljit_set_label(sljit_emit_jump(compiler, (type)), (label)) #define JUMPHERE(jump) \ sljit_set_label((jump), sljit_emit_label(compiler)) #define SET_LABEL(jump, label) \ sljit_set_label((jump), (label)) #define CMP(type, src1, src1w, src2, src2w) \ sljit_emit_cmp(compiler, (type), (src1), (src1w), (src2), (src2w)) #define CMPTO(type, src1, src1w, src2, src2w, label) \ sljit_set_label(sljit_emit_cmp(compiler, (type), (src1), (src1w), (src2), (src2w)), (label)) #define OP_FLAGS(op, dst, dstw, type) \ sljit_emit_op_flags(compiler, (op), (dst), (dstw), (type)) #define GET_LOCAL_BASE(dst, dstw, offset) \ sljit_get_local_base(compiler, (dst), (dstw), (offset)) #define READ_CHAR_MAX 0x7fffffff #define INVALID_UTF_CHAR 888 static pcre_uchar *bracketend(pcre_uchar *cc) { SLJIT_ASSERT((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)); do cc += GET(cc, 1); while (*cc == OP_ALT); SLJIT_ASSERT(*cc >= OP_KET && *cc <= OP_KETRPOS); cc += 1 + LINK_SIZE; return cc; } static int no_alternatives(pcre_uchar *cc) { int count = 0; SLJIT_ASSERT((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)); do { cc += GET(cc, 1); count++; } while (*cc == OP_ALT); SLJIT_ASSERT(*cc >= OP_KET && *cc <= OP_KETRPOS); return count; } /* Functions whose might need modification for all new supported opcodes: next_opcode check_opcode_types set_private_data_ptrs get_framesize init_frame get_private_data_copy_length copy_private_data compile_matchingpath compile_backtrackingpath */ static pcre_uchar *next_opcode(compiler_common *common, pcre_uchar *cc) { SLJIT_UNUSED_ARG(common); switch(*cc) { case OP_SOD: case OP_SOM: case OP_SET_SOM: case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: case OP_ALLANY: case OP_NOTPROP: case OP_PROP: case OP_ANYNL: case OP_NOT_HSPACE: case OP_HSPACE: case OP_NOT_VSPACE: case OP_VSPACE: case OP_EXTUNI: case OP_EODN: case OP_EOD: case OP_CIRC: case OP_CIRCM: case OP_DOLL: case OP_DOLLM: case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSSTAR: case OP_CRPOSPLUS: case OP_CRPOSQUERY: case OP_CRPOSRANGE: case OP_CLASS: case OP_NCLASS: case OP_REF: case OP_REFI: case OP_DNREF: case OP_DNREFI: case OP_RECURSE: case OP_CALLOUT: case OP_ALT: case OP_KET: case OP_KETRMAX: case OP_KETRMIN: case OP_KETRPOS: case OP_REVERSE: case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_ONCE_NC: case OP_BRA: case OP_BRAPOS: case OP_CBRA: case OP_CBRAPOS: case OP_COND: case OP_SBRA: case OP_SBRAPOS: case OP_SCBRA: case OP_SCBRAPOS: case OP_SCOND: case OP_CREF: case OP_DNCREF: case OP_RREF: case OP_DNRREF: case OP_DEF: case OP_BRAZERO: case OP_BRAMINZERO: case OP_BRAPOSZERO: case OP_PRUNE: case OP_SKIP: case OP_THEN: case OP_COMMIT: case OP_FAIL: case OP_ACCEPT: case OP_ASSERT_ACCEPT: case OP_CLOSE: case OP_SKIPZERO: return cc + PRIV(OP_lengths)[*cc]; case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_UPTOI: case OP_MINUPTOI: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: cc += PRIV(OP_lengths)[*cc]; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif return cc; /* Special cases. */ case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: case OP_TYPEPOSUPTO: return cc + PRIV(OP_lengths)[*cc] - 1; case OP_ANYBYTE: #ifdef SUPPORT_UTF if (common->utf) return NULL; #endif return cc + 1; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: return cc + GET(cc, 1); #endif case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: return cc + 1 + 2 + cc[1]; default: /* All opcodes are supported now! */ SLJIT_UNREACHABLE(); return NULL; } } static BOOL check_opcode_types(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend) { int count; pcre_uchar *slot; pcre_uchar *assert_back_end = cc - 1; /* Calculate important variables (like stack size) and checks whether all opcodes are supported. */ while (cc < ccend) { switch(*cc) { case OP_SET_SOM: common->has_set_som = TRUE; common->might_be_empty = TRUE; cc += 1; break; case OP_REF: case OP_REFI: common->optimized_cbracket[GET2(cc, 1)] = 0; cc += 1 + IMM2_SIZE; break; case OP_CBRAPOS: case OP_SCBRAPOS: common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] = 0; cc += 1 + LINK_SIZE + IMM2_SIZE; break; case OP_COND: case OP_SCOND: /* Only AUTO_CALLOUT can insert this opcode. We do not intend to support this case. */ if (cc[1 + LINK_SIZE] == OP_CALLOUT) return FALSE; cc += 1 + LINK_SIZE; break; case OP_CREF: common->optimized_cbracket[GET2(cc, 1)] = 0; cc += 1 + IMM2_SIZE; break; case OP_DNREF: case OP_DNREFI: case OP_DNCREF: count = GET2(cc, 1 + IMM2_SIZE); slot = common->name_table + GET2(cc, 1) * common->name_entry_size; while (count-- > 0) { common->optimized_cbracket[GET2(slot, 0)] = 0; slot += common->name_entry_size; } cc += 1 + 2 * IMM2_SIZE; break; case OP_RECURSE: /* Set its value only once. */ if (common->recursive_head_ptr == 0) { common->recursive_head_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } cc += 1 + LINK_SIZE; break; case OP_CALLOUT: if (common->capture_last_ptr == 0) { common->capture_last_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } cc += 2 + 2 * LINK_SIZE; break; case OP_ASSERTBACK: slot = bracketend(cc); if (slot > assert_back_end) assert_back_end = slot; cc += 1 + LINK_SIZE; break; case OP_THEN_ARG: common->has_then = TRUE; common->control_head_ptr = 1; /* Fall through. */ case OP_PRUNE_ARG: case OP_MARK: if (common->mark_ptr == 0) { common->mark_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } cc += 1 + 2 + cc[1]; break; case OP_THEN: common->has_then = TRUE; common->control_head_ptr = 1; cc += 1; break; case OP_SKIP: if (cc < assert_back_end) common->has_skip_in_assert_back = TRUE; cc += 1; break; case OP_SKIP_ARG: common->control_head_ptr = 1; common->has_skip_arg = TRUE; if (cc < assert_back_end) common->has_skip_in_assert_back = TRUE; cc += 1 + 2 + cc[1]; break; default: cc = next_opcode(common, cc); if (cc == NULL) return FALSE; break; } } return TRUE; } static BOOL is_accelerated_repeat(pcre_uchar *cc) { switch(*cc) { case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: return (cc[1] != OP_ANYNL && cc[1] != OP_EXTUNI); case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_POSSTAR: case OP_POSPLUS: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_POSSTARI: case OP_POSPLUSI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: return TRUE; case OP_CLASS: case OP_NCLASS: #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: cc += (*cc == OP_XCLASS) ? GET(cc, 1) : (int)(1 + (32 / sizeof(pcre_uchar))); #else cc += (1 + (32 / sizeof(pcre_uchar))); #endif switch(*cc) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRPOSSTAR: case OP_CRPOSPLUS: return TRUE; } break; } return FALSE; } static SLJIT_INLINE BOOL detect_fast_forward_skip(compiler_common *common, int *private_data_start) { pcre_uchar *cc = common->start; pcre_uchar *end; /* Skip not repeated brackets. */ while (TRUE) { switch(*cc) { case OP_SOD: case OP_SOM: case OP_SET_SOM: case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_EODN: case OP_EOD: case OP_CIRC: case OP_CIRCM: case OP_DOLL: case OP_DOLLM: /* Zero width assertions. */ cc++; continue; } if (*cc != OP_BRA && *cc != OP_CBRA) break; end = cc + GET(cc, 1); if (*end != OP_KET || PRIVATE_DATA(end) != 0) return FALSE; if (*cc == OP_CBRA) { if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) return FALSE; cc += IMM2_SIZE; } cc += 1 + LINK_SIZE; } if (is_accelerated_repeat(cc)) { common->fast_forward_bc_ptr = cc; common->private_data_ptrs[(cc + 1) - common->start] = *private_data_start; *private_data_start += sizeof(sljit_sw); return TRUE; } return FALSE; } static SLJIT_INLINE void detect_fast_fail(compiler_common *common, pcre_uchar *cc, int *private_data_start, sljit_s32 depth) { pcre_uchar *next_alt; SLJIT_ASSERT(*cc == OP_BRA || *cc == OP_CBRA); if (*cc == OP_CBRA && common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) return; next_alt = bracketend(cc) - (1 + LINK_SIZE); if (*next_alt != OP_KET || PRIVATE_DATA(next_alt) != 0) return; do { next_alt = cc + GET(cc, 1); cc += 1 + LINK_SIZE + ((*cc == OP_CBRA) ? IMM2_SIZE : 0); while (TRUE) { switch(*cc) { case OP_SOD: case OP_SOM: case OP_SET_SOM: case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_EODN: case OP_EOD: case OP_CIRC: case OP_CIRCM: case OP_DOLL: case OP_DOLLM: /* Zero width assertions. */ cc++; continue; } break; } if (depth > 0 && (*cc == OP_BRA || *cc == OP_CBRA)) detect_fast_fail(common, cc, private_data_start, depth - 1); if (is_accelerated_repeat(cc)) { common->private_data_ptrs[(cc + 1) - common->start] = *private_data_start; if (common->fast_fail_start_ptr == 0) common->fast_fail_start_ptr = *private_data_start; *private_data_start += sizeof(sljit_sw); common->fast_fail_end_ptr = *private_data_start; if (*private_data_start > SLJIT_MAX_LOCAL_SIZE) return; } cc = next_alt; } while (*cc == OP_ALT); } static int get_class_iterator_size(pcre_uchar *cc) { sljit_u32 min; sljit_u32 max; switch(*cc) { case OP_CRSTAR: case OP_CRPLUS: return 2; case OP_CRMINSTAR: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: return 1; case OP_CRRANGE: case OP_CRMINRANGE: min = GET2(cc, 1); max = GET2(cc, 1 + IMM2_SIZE); if (max == 0) return (*cc == OP_CRRANGE) ? 2 : 1; max -= min; if (max > 2) max = 2; return max; default: return 0; } } static BOOL detect_repeat(compiler_common *common, pcre_uchar *begin) { pcre_uchar *end = bracketend(begin); pcre_uchar *next; pcre_uchar *next_end; pcre_uchar *max_end; pcre_uchar type; sljit_sw length = end - begin; int min, max, i; /* Detect fixed iterations first. */ if (end[-(1 + LINK_SIZE)] != OP_KET) return FALSE; /* Already detected repeat. */ if (common->private_data_ptrs[end - common->start - LINK_SIZE] != 0) return TRUE; next = end; min = 1; while (1) { if (*next != *begin) break; next_end = bracketend(next); if (next_end - next != length || memcmp(begin, next, IN_UCHARS(length)) != 0) break; next = next_end; min++; } if (min == 2) return FALSE; max = 0; max_end = next; if (*next == OP_BRAZERO || *next == OP_BRAMINZERO) { type = *next; while (1) { if (next[0] != type || next[1] != OP_BRA || next[2 + LINK_SIZE] != *begin) break; next_end = bracketend(next + 2 + LINK_SIZE); if (next_end - next != (length + 2 + LINK_SIZE) || memcmp(begin, next + 2 + LINK_SIZE, IN_UCHARS(length)) != 0) break; next = next_end; max++; } if (next[0] == type && next[1] == *begin && max >= 1) { next_end = bracketend(next + 1); if (next_end - next == (length + 1) && memcmp(begin, next + 1, IN_UCHARS(length)) == 0) { for (i = 0; i < max; i++, next_end += 1 + LINK_SIZE) if (*next_end != OP_KET) break; if (i == max) { common->private_data_ptrs[max_end - common->start - LINK_SIZE] = next_end - max_end; common->private_data_ptrs[max_end - common->start - LINK_SIZE + 1] = (type == OP_BRAZERO) ? OP_UPTO : OP_MINUPTO; /* +2 the original and the last. */ common->private_data_ptrs[max_end - common->start - LINK_SIZE + 2] = max + 2; if (min == 1) return TRUE; min--; max_end -= (1 + LINK_SIZE) + GET(max_end, -LINK_SIZE); } } } } if (min >= 3) { common->private_data_ptrs[end - common->start - LINK_SIZE] = max_end - end; common->private_data_ptrs[end - common->start - LINK_SIZE + 1] = OP_EXACT; common->private_data_ptrs[end - common->start - LINK_SIZE + 2] = min; return TRUE; } return FALSE; } #define CASE_ITERATOR_PRIVATE_DATA_1 \ case OP_MINSTAR: \ case OP_MINPLUS: \ case OP_QUERY: \ case OP_MINQUERY: \ case OP_MINSTARI: \ case OP_MINPLUSI: \ case OP_QUERYI: \ case OP_MINQUERYI: \ case OP_NOTMINSTAR: \ case OP_NOTMINPLUS: \ case OP_NOTQUERY: \ case OP_NOTMINQUERY: \ case OP_NOTMINSTARI: \ case OP_NOTMINPLUSI: \ case OP_NOTQUERYI: \ case OP_NOTMINQUERYI: #define CASE_ITERATOR_PRIVATE_DATA_2A \ case OP_STAR: \ case OP_PLUS: \ case OP_STARI: \ case OP_PLUSI: \ case OP_NOTSTAR: \ case OP_NOTPLUS: \ case OP_NOTSTARI: \ case OP_NOTPLUSI: #define CASE_ITERATOR_PRIVATE_DATA_2B \ case OP_UPTO: \ case OP_MINUPTO: \ case OP_UPTOI: \ case OP_MINUPTOI: \ case OP_NOTUPTO: \ case OP_NOTMINUPTO: \ case OP_NOTUPTOI: \ case OP_NOTMINUPTOI: #define CASE_ITERATOR_TYPE_PRIVATE_DATA_1 \ case OP_TYPEMINSTAR: \ case OP_TYPEMINPLUS: \ case OP_TYPEQUERY: \ case OP_TYPEMINQUERY: #define CASE_ITERATOR_TYPE_PRIVATE_DATA_2A \ case OP_TYPESTAR: \ case OP_TYPEPLUS: #define CASE_ITERATOR_TYPE_PRIVATE_DATA_2B \ case OP_TYPEUPTO: \ case OP_TYPEMINUPTO: static void set_private_data_ptrs(compiler_common *common, int *private_data_start, pcre_uchar *ccend) { pcre_uchar *cc = common->start; pcre_uchar *alternative; pcre_uchar *end = NULL; int private_data_ptr = *private_data_start; int space, size, bracketlen; BOOL repeat_check = TRUE; while (cc < ccend) { space = 0; size = 0; bracketlen = 0; if (private_data_ptr > SLJIT_MAX_LOCAL_SIZE) break; if (repeat_check && (*cc == OP_ONCE || *cc == OP_ONCE_NC || *cc == OP_BRA || *cc == OP_CBRA || *cc == OP_COND)) { if (detect_repeat(common, cc)) { /* These brackets are converted to repeats, so no global based single character repeat is allowed. */ if (cc >= end) end = bracketend(cc); } } repeat_check = TRUE; switch(*cc) { case OP_KET: if (common->private_data_ptrs[cc + 1 - common->start] != 0) { common->private_data_ptrs[cc - common->start] = private_data_ptr; private_data_ptr += sizeof(sljit_sw); cc += common->private_data_ptrs[cc + 1 - common->start]; } cc += 1 + LINK_SIZE; break; case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_ONCE_NC: case OP_BRAPOS: case OP_SBRA: case OP_SBRAPOS: case OP_SCOND: common->private_data_ptrs[cc - common->start] = private_data_ptr; private_data_ptr += sizeof(sljit_sw); bracketlen = 1 + LINK_SIZE; break; case OP_CBRAPOS: case OP_SCBRAPOS: common->private_data_ptrs[cc - common->start] = private_data_ptr; private_data_ptr += sizeof(sljit_sw); bracketlen = 1 + LINK_SIZE + IMM2_SIZE; break; case OP_COND: /* Might be a hidden SCOND. */ alternative = cc + GET(cc, 1); if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) { common->private_data_ptrs[cc - common->start] = private_data_ptr; private_data_ptr += sizeof(sljit_sw); } bracketlen = 1 + LINK_SIZE; break; case OP_BRA: bracketlen = 1 + LINK_SIZE; break; case OP_CBRA: case OP_SCBRA: bracketlen = 1 + LINK_SIZE + IMM2_SIZE; break; case OP_BRAZERO: case OP_BRAMINZERO: case OP_BRAPOSZERO: repeat_check = FALSE; size = 1; break; CASE_ITERATOR_PRIVATE_DATA_1 space = 1; size = -2; break; CASE_ITERATOR_PRIVATE_DATA_2A space = 2; size = -2; break; CASE_ITERATOR_PRIVATE_DATA_2B space = 2; size = -(2 + IMM2_SIZE); break; CASE_ITERATOR_TYPE_PRIVATE_DATA_1 space = 1; size = 1; break; CASE_ITERATOR_TYPE_PRIVATE_DATA_2A if (cc[1] != OP_ANYNL && cc[1] != OP_EXTUNI) space = 2; size = 1; break; case OP_TYPEUPTO: if (cc[1 + IMM2_SIZE] != OP_ANYNL && cc[1 + IMM2_SIZE] != OP_EXTUNI) space = 2; size = 1 + IMM2_SIZE; break; case OP_TYPEMINUPTO: space = 2; size = 1 + IMM2_SIZE; break; case OP_CLASS: case OP_NCLASS: space = get_class_iterator_size(cc + size); size = 1 + 32 / sizeof(pcre_uchar); break; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: space = get_class_iterator_size(cc + size); size = GET(cc, 1); break; #endif default: cc = next_opcode(common, cc); SLJIT_ASSERT(cc != NULL); break; } /* Character iterators, which are not inside a repeated bracket, gets a private slot instead of allocating it on the stack. */ if (space > 0 && cc >= end) { common->private_data_ptrs[cc - common->start] = private_data_ptr; private_data_ptr += sizeof(sljit_sw) * space; } if (size != 0) { if (size < 0) { cc += -size; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif } else cc += size; } if (bracketlen > 0) { if (cc >= end) { end = bracketend(cc); if (end[-1 - LINK_SIZE] == OP_KET) end = NULL; } cc += bracketlen; } } *private_data_start = private_data_ptr; } /* Returns with a frame_types (always < 0) if no need for frame. */ static int get_framesize(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL recursive, BOOL *needs_control_head) { int length = 0; int possessive = 0; BOOL stack_restore = FALSE; BOOL setsom_found = recursive; BOOL setmark_found = recursive; /* The last capture is a local variable even for recursions. */ BOOL capture_last_found = FALSE; #if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD SLJIT_ASSERT(common->control_head_ptr != 0); *needs_control_head = TRUE; #else *needs_control_head = FALSE; #endif if (ccend == NULL) { ccend = bracketend(cc) - (1 + LINK_SIZE); if (!recursive && (*cc == OP_CBRAPOS || *cc == OP_SCBRAPOS)) { possessive = length = (common->capture_last_ptr != 0) ? 5 : 3; /* This is correct regardless of common->capture_last_ptr. */ capture_last_found = TRUE; } cc = next_opcode(common, cc); } SLJIT_ASSERT(cc != NULL); while (cc < ccend) switch(*cc) { case OP_SET_SOM: SLJIT_ASSERT(common->has_set_som); stack_restore = TRUE; if (!setsom_found) { length += 2; setsom_found = TRUE; } cc += 1; break; case OP_MARK: case OP_PRUNE_ARG: case OP_THEN_ARG: SLJIT_ASSERT(common->mark_ptr != 0); stack_restore = TRUE; if (!setmark_found) { length += 2; setmark_found = TRUE; } if (common->control_head_ptr != 0) *needs_control_head = TRUE; cc += 1 + 2 + cc[1]; break; case OP_RECURSE: stack_restore = TRUE; if (common->has_set_som && !setsom_found) { length += 2; setsom_found = TRUE; } if (common->mark_ptr != 0 && !setmark_found) { length += 2; setmark_found = TRUE; } if (common->capture_last_ptr != 0 && !capture_last_found) { length += 2; capture_last_found = TRUE; } cc += 1 + LINK_SIZE; break; case OP_CBRA: case OP_CBRAPOS: case OP_SCBRA: case OP_SCBRAPOS: stack_restore = TRUE; if (common->capture_last_ptr != 0 && !capture_last_found) { length += 2; capture_last_found = TRUE; } length += 3; cc += 1 + LINK_SIZE + IMM2_SIZE; break; case OP_THEN: stack_restore = TRUE; if (common->control_head_ptr != 0) *needs_control_head = TRUE; cc ++; break; default: stack_restore = TRUE; /* Fall through. */ case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: case OP_ALLANY: case OP_ANYBYTE: case OP_NOTPROP: case OP_PROP: case OP_ANYNL: case OP_NOT_HSPACE: case OP_HSPACE: case OP_NOT_VSPACE: case OP_VSPACE: case OP_EXTUNI: case OP_EODN: case OP_EOD: case OP_CIRC: case OP_CIRCM: case OP_DOLL: case OP_DOLLM: case OP_CHAR: case OP_CHARI: case OP_NOT: case OP_NOTI: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: case OP_TYPEEXACT: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: case OP_TYPEPOSUPTO: case OP_CLASS: case OP_NCLASS: case OP_XCLASS: case OP_CALLOUT: cc = next_opcode(common, cc); SLJIT_ASSERT(cc != NULL); break; } /* Possessive quantifiers can use a special case. */ if (SLJIT_UNLIKELY(possessive == length)) return stack_restore ? no_frame : no_stack; if (length > 0) return length + 1; return stack_restore ? no_frame : no_stack; } static void init_frame(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, int stackpos, int stacktop, BOOL recursive) { DEFINE_COMPILER; BOOL setsom_found = recursive; BOOL setmark_found = recursive; /* The last capture is a local variable even for recursions. */ BOOL capture_last_found = FALSE; int offset; /* >= 1 + shortest item size (2) */ SLJIT_UNUSED_ARG(stacktop); SLJIT_ASSERT(stackpos >= stacktop + 2); stackpos = STACK(stackpos); if (ccend == NULL) { ccend = bracketend(cc) - (1 + LINK_SIZE); if (recursive || (*cc != OP_CBRAPOS && *cc != OP_SCBRAPOS)) cc = next_opcode(common, cc); } SLJIT_ASSERT(cc != NULL); while (cc < ccend) switch(*cc) { case OP_SET_SOM: SLJIT_ASSERT(common->has_set_som); if (!setsom_found) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -OVECTOR(0)); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); setsom_found = TRUE; } cc += 1; break; case OP_MARK: case OP_PRUNE_ARG: case OP_THEN_ARG: SLJIT_ASSERT(common->mark_ptr != 0); if (!setmark_found) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->mark_ptr); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); setmark_found = TRUE; } cc += 1 + 2 + cc[1]; break; case OP_RECURSE: if (common->has_set_som && !setsom_found) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -OVECTOR(0)); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); setsom_found = TRUE; } if (common->mark_ptr != 0 && !setmark_found) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->mark_ptr); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); setmark_found = TRUE; } if (common->capture_last_ptr != 0 && !capture_last_found) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->capture_last_ptr); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); capture_last_found = TRUE; } cc += 1 + LINK_SIZE; break; case OP_CBRA: case OP_CBRAPOS: case OP_SCBRA: case OP_SCBRAPOS: if (common->capture_last_ptr != 0 && !capture_last_found) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->capture_last_ptr); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); capture_last_found = TRUE; } offset = (GET2(cc, 1 + LINK_SIZE)) << 1; OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, OVECTOR(offset)); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); stackpos -= (int)sizeof(sljit_sw); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP2, 0); stackpos -= (int)sizeof(sljit_sw); cc += 1 + LINK_SIZE + IMM2_SIZE; break; default: cc = next_opcode(common, cc); SLJIT_ASSERT(cc != NULL); break; } OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, 0); SLJIT_ASSERT(stackpos == STACK(stacktop)); } static SLJIT_INLINE int get_private_data_copy_length(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL needs_control_head) { int private_data_length = needs_control_head ? 3 : 2; int size; pcre_uchar *alternative; /* Calculate the sum of the private machine words. */ while (cc < ccend) { size = 0; switch(*cc) { case OP_KET: if (PRIVATE_DATA(cc) != 0) { private_data_length++; SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0); cc += PRIVATE_DATA(cc + 1); } cc += 1 + LINK_SIZE; break; case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_ONCE_NC: case OP_BRAPOS: case OP_SBRA: case OP_SBRAPOS: case OP_SCOND: private_data_length++; SLJIT_ASSERT(PRIVATE_DATA(cc) != 0); cc += 1 + LINK_SIZE; break; case OP_CBRA: case OP_SCBRA: if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) private_data_length++; cc += 1 + LINK_SIZE + IMM2_SIZE; break; case OP_CBRAPOS: case OP_SCBRAPOS: private_data_length += 2; cc += 1 + LINK_SIZE + IMM2_SIZE; break; case OP_COND: /* Might be a hidden SCOND. */ alternative = cc + GET(cc, 1); if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) private_data_length++; cc += 1 + LINK_SIZE; break; CASE_ITERATOR_PRIVATE_DATA_1 if (PRIVATE_DATA(cc)) private_data_length++; cc += 2; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; CASE_ITERATOR_PRIVATE_DATA_2A if (PRIVATE_DATA(cc)) private_data_length += 2; cc += 2; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; CASE_ITERATOR_PRIVATE_DATA_2B if (PRIVATE_DATA(cc)) private_data_length += 2; cc += 2 + IMM2_SIZE; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; CASE_ITERATOR_TYPE_PRIVATE_DATA_1 if (PRIVATE_DATA(cc)) private_data_length++; cc += 1; break; CASE_ITERATOR_TYPE_PRIVATE_DATA_2A if (PRIVATE_DATA(cc)) private_data_length += 2; cc += 1; break; CASE_ITERATOR_TYPE_PRIVATE_DATA_2B if (PRIVATE_DATA(cc)) private_data_length += 2; cc += 1 + IMM2_SIZE; break; case OP_CLASS: case OP_NCLASS: #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(pcre_uchar); #else size = 1 + 32 / (int)sizeof(pcre_uchar); #endif if (PRIVATE_DATA(cc)) private_data_length += get_class_iterator_size(cc + size); cc += size; break; default: cc = next_opcode(common, cc); SLJIT_ASSERT(cc != NULL); break; } } SLJIT_ASSERT(cc == ccend); return private_data_length; } static void copy_private_data(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL save, int stackptr, int stacktop, BOOL needs_control_head) { DEFINE_COMPILER; int srcw[2]; int count, size; BOOL tmp1next = TRUE; BOOL tmp1empty = TRUE; BOOL tmp2empty = TRUE; pcre_uchar *alternative; enum { loop, end } status; status = loop; stackptr = STACK(stackptr); stacktop = STACK(stacktop - 1); if (!save) { stacktop -= (needs_control_head ? 2 : 1) * sizeof(sljit_sw); if (stackptr < stacktop) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), stackptr); stackptr += sizeof(sljit_sw); tmp1empty = FALSE; } if (stackptr < stacktop) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), stackptr); stackptr += sizeof(sljit_sw); tmp2empty = FALSE; } /* The tmp1next must be TRUE in either way. */ } SLJIT_ASSERT(common->recursive_head_ptr != 0); do { count = 0; if (cc >= ccend) { if (!save) break; count = 1; srcw[0] = common->recursive_head_ptr; if (needs_control_head) { SLJIT_ASSERT(common->control_head_ptr != 0); count = 2; srcw[0] = common->control_head_ptr; srcw[1] = common->recursive_head_ptr; } status = end; } else switch(*cc) { case OP_KET: if (PRIVATE_DATA(cc) != 0) { count = 1; srcw[0] = PRIVATE_DATA(cc); SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0); cc += PRIVATE_DATA(cc + 1); } cc += 1 + LINK_SIZE; break; case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_ONCE_NC: case OP_BRAPOS: case OP_SBRA: case OP_SBRAPOS: case OP_SCOND: count = 1; srcw[0] = PRIVATE_DATA(cc); SLJIT_ASSERT(srcw[0] != 0); cc += 1 + LINK_SIZE; break; case OP_CBRA: case OP_SCBRA: if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) { count = 1; srcw[0] = OVECTOR_PRIV(GET2(cc, 1 + LINK_SIZE)); } cc += 1 + LINK_SIZE + IMM2_SIZE; break; case OP_CBRAPOS: case OP_SCBRAPOS: count = 2; srcw[0] = PRIVATE_DATA(cc); srcw[1] = OVECTOR_PRIV(GET2(cc, 1 + LINK_SIZE)); SLJIT_ASSERT(srcw[0] != 0 && srcw[1] != 0); cc += 1 + LINK_SIZE + IMM2_SIZE; break; case OP_COND: /* Might be a hidden SCOND. */ alternative = cc + GET(cc, 1); if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) { count = 1; srcw[0] = PRIVATE_DATA(cc); SLJIT_ASSERT(srcw[0] != 0); } cc += 1 + LINK_SIZE; break; CASE_ITERATOR_PRIVATE_DATA_1 if (PRIVATE_DATA(cc)) { count = 1; srcw[0] = PRIVATE_DATA(cc); } cc += 2; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; CASE_ITERATOR_PRIVATE_DATA_2A if (PRIVATE_DATA(cc)) { count = 2; srcw[0] = PRIVATE_DATA(cc); srcw[1] = PRIVATE_DATA(cc) + sizeof(sljit_sw); } cc += 2; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; CASE_ITERATOR_PRIVATE_DATA_2B if (PRIVATE_DATA(cc)) { count = 2; srcw[0] = PRIVATE_DATA(cc); srcw[1] = PRIVATE_DATA(cc) + sizeof(sljit_sw); } cc += 2 + IMM2_SIZE; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); #endif break; CASE_ITERATOR_TYPE_PRIVATE_DATA_1 if (PRIVATE_DATA(cc)) { count = 1; srcw[0] = PRIVATE_DATA(cc); } cc += 1; break; CASE_ITERATOR_TYPE_PRIVATE_DATA_2A if (PRIVATE_DATA(cc)) { count = 2; srcw[0] = PRIVATE_DATA(cc); srcw[1] = srcw[0] + sizeof(sljit_sw); } cc += 1; break; CASE_ITERATOR_TYPE_PRIVATE_DATA_2B if (PRIVATE_DATA(cc)) { count = 2; srcw[0] = PRIVATE_DATA(cc); srcw[1] = srcw[0] + sizeof(sljit_sw); } cc += 1 + IMM2_SIZE; break; case OP_CLASS: case OP_NCLASS: #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(pcre_uchar); #else size = 1 + 32 / (int)sizeof(pcre_uchar); #endif if (PRIVATE_DATA(cc)) switch(get_class_iterator_size(cc + size)) { case 1: count = 1; srcw[0] = PRIVATE_DATA(cc); break; case 2: count = 2; srcw[0] = PRIVATE_DATA(cc); srcw[1] = srcw[0] + sizeof(sljit_sw); break; default: SLJIT_UNREACHABLE(); break; } cc += size; break; default: cc = next_opcode(common, cc); SLJIT_ASSERT(cc != NULL); break; } while (count > 0) { count--; if (save) { if (tmp1next) { if (!tmp1empty) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); stackptr += sizeof(sljit_sw); } OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), srcw[count]); tmp1empty = FALSE; tmp1next = FALSE; } else { if (!tmp2empty) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); stackptr += sizeof(sljit_sw); } OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), srcw[count]); tmp2empty = FALSE; tmp1next = TRUE; } } else { if (tmp1next) { SLJIT_ASSERT(!tmp1empty); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), srcw[count], TMP1, 0); tmp1empty = stackptr >= stacktop; if (!tmp1empty) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), stackptr); stackptr += sizeof(sljit_sw); } tmp1next = FALSE; } else { SLJIT_ASSERT(!tmp2empty); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), srcw[count], TMP2, 0); tmp2empty = stackptr >= stacktop; if (!tmp2empty) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), stackptr); stackptr += sizeof(sljit_sw); } tmp1next = TRUE; } } } } while (status != end); if (save) { if (tmp1next) { if (!tmp1empty) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); stackptr += sizeof(sljit_sw); } if (!tmp2empty) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); stackptr += sizeof(sljit_sw); } } else { if (!tmp2empty) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); stackptr += sizeof(sljit_sw); } if (!tmp1empty) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); stackptr += sizeof(sljit_sw); } } } SLJIT_ASSERT(cc == ccend && stackptr == stacktop && (save || (tmp1empty && tmp2empty))); } static SLJIT_INLINE pcre_uchar *set_then_offsets(compiler_common *common, pcre_uchar *cc, sljit_u8 *current_offset) { pcre_uchar *end = bracketend(cc); BOOL has_alternatives = cc[GET(cc, 1)] == OP_ALT; /* Assert captures then. */ if (*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) current_offset = NULL; /* Conditional block does not. */ if (*cc == OP_COND || *cc == OP_SCOND) has_alternatives = FALSE; cc = next_opcode(common, cc); if (has_alternatives) current_offset = common->then_offsets + (cc - common->start); while (cc < end) { if ((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)) cc = set_then_offsets(common, cc, current_offset); else { if (*cc == OP_ALT && has_alternatives) current_offset = common->then_offsets + (cc + 1 + LINK_SIZE - common->start); if (*cc >= OP_THEN && *cc <= OP_THEN_ARG && current_offset != NULL) *current_offset = 1; cc = next_opcode(common, cc); } } return end; } #undef CASE_ITERATOR_PRIVATE_DATA_1 #undef CASE_ITERATOR_PRIVATE_DATA_2A #undef CASE_ITERATOR_PRIVATE_DATA_2B #undef CASE_ITERATOR_TYPE_PRIVATE_DATA_1 #undef CASE_ITERATOR_TYPE_PRIVATE_DATA_2A #undef CASE_ITERATOR_TYPE_PRIVATE_DATA_2B static SLJIT_INLINE BOOL is_powerof2(unsigned int value) { return (value & (value - 1)) == 0; } static SLJIT_INLINE void set_jumps(jump_list *list, struct sljit_label *label) { while (list) { /* sljit_set_label is clever enough to do nothing if either the jump or the label is NULL. */ SET_LABEL(list->jump, label); list = list->next; } } static SLJIT_INLINE void add_jump(struct sljit_compiler *compiler, jump_list **list, struct sljit_jump *jump) { jump_list *list_item = sljit_alloc_memory(compiler, sizeof(jump_list)); if (list_item) { list_item->next = *list; list_item->jump = jump; *list = list_item; } } static void add_stub(compiler_common *common, struct sljit_jump *start) { DEFINE_COMPILER; stub_list *list_item = sljit_alloc_memory(compiler, sizeof(stub_list)); if (list_item) { list_item->start = start; list_item->quit = LABEL(); list_item->next = common->stubs; common->stubs = list_item; } } static void flush_stubs(compiler_common *common) { DEFINE_COMPILER; stub_list *list_item = common->stubs; while (list_item) { JUMPHERE(list_item->start); add_jump(compiler, &common->stackalloc, JUMP(SLJIT_FAST_CALL)); JUMPTO(SLJIT_JUMP, list_item->quit); list_item = list_item->next; } common->stubs = NULL; } static void add_label_addr(compiler_common *common, sljit_uw *update_addr) { DEFINE_COMPILER; label_addr_list *label_addr; label_addr = sljit_alloc_memory(compiler, sizeof(label_addr_list)); if (label_addr == NULL) return; label_addr->label = LABEL(); label_addr->update_addr = update_addr; label_addr->next = common->label_addrs; common->label_addrs = label_addr; } static SLJIT_INLINE void count_match(compiler_common *common) { DEFINE_COMPILER; OP2(SLJIT_SUB | SLJIT_SET_Z, COUNT_MATCH, 0, COUNT_MATCH, 0, SLJIT_IMM, 1); add_jump(compiler, &common->calllimit, JUMP(SLJIT_ZERO)); } static SLJIT_INLINE void allocate_stack(compiler_common *common, int size) { /* May destroy all locals and registers except TMP2. */ DEFINE_COMPILER; SLJIT_ASSERT(size > 0); OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, size * sizeof(sljit_sw)); #ifdef DESTROY_REGISTERS OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 12345); OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP1, 0); #endif add_stub(common, CMP(SLJIT_LESS, STACK_TOP, 0, STACK_LIMIT, 0)); } static SLJIT_INLINE void free_stack(compiler_common *common, int size) { DEFINE_COMPILER; SLJIT_ASSERT(size > 0); OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, size * sizeof(sljit_sw)); } static sljit_uw * allocate_read_only_data(compiler_common *common, sljit_uw size) { DEFINE_COMPILER; sljit_uw *result; if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return NULL; result = (sljit_uw *)SLJIT_MALLOC(size + sizeof(sljit_uw), compiler->allocator_data); if (SLJIT_UNLIKELY(result == NULL)) { sljit_set_compiler_memory_error(compiler); return NULL; } *(void**)result = common->read_only_data_head; common->read_only_data_head = (void *)result; return result + 1; } static void free_read_only_data(void *current, void *allocator_data) { void *next; SLJIT_UNUSED_ARG(allocator_data); while (current != NULL) { next = *(void**)current; SLJIT_FREE(current, allocator_data); current = next; } } static SLJIT_INLINE void reset_ovector(compiler_common *common, int length) { DEFINE_COMPILER; struct sljit_label *loop; int i; /* At this point we can freely use all temporary registers. */ SLJIT_ASSERT(length > 1); /* TMP1 returns with begin - 1. */ OP2(SLJIT_SUB, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_S0), SLJIT_OFFSETOF(jit_arguments, begin), SLJIT_IMM, IN_UCHARS(1)); if (length < 8) { for (i = 1; i < length; i++) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(i), SLJIT_R0, 0); } else { if (sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_SUPP | SLJIT_MEM_STORE | SLJIT_MEM_PRE, SLJIT_R0, SLJIT_MEM1(SLJIT_R1), sizeof(sljit_sw)) == SLJIT_SUCCESS) { GET_LOCAL_BASE(SLJIT_R1, 0, OVECTOR_START); OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_IMM, length - 1); loop = LABEL(); sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_STORE | SLJIT_MEM_PRE, SLJIT_R0, SLJIT_MEM1(SLJIT_R1), sizeof(sljit_sw)); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, loop); } else { GET_LOCAL_BASE(SLJIT_R1, 0, OVECTOR_START + sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_IMM, length - 1); loop = LABEL(); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_R1), 0, SLJIT_R0, 0); OP2(SLJIT_ADD, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, sizeof(sljit_sw)); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, loop); } } } static SLJIT_INLINE void reset_fast_fail(compiler_common *common) { DEFINE_COMPILER; sljit_s32 i; SLJIT_ASSERT(common->fast_fail_start_ptr < common->fast_fail_end_ptr); OP2(SLJIT_SUB, TMP1, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); for (i = common->fast_fail_start_ptr; i < common->fast_fail_end_ptr; i += sizeof(sljit_sw)) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), i, TMP1, 0); } static SLJIT_INLINE void do_reset_match(compiler_common *common, int length) { DEFINE_COMPILER; struct sljit_label *loop; int i; SLJIT_ASSERT(length > 1); /* OVECTOR(1) contains the "string begin - 1" constant. */ if (length > 2) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); if (length < 8) { for (i = 2; i < length; i++) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(i), TMP1, 0); } else { if (sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_SUPP | SLJIT_MEM_STORE | SLJIT_MEM_PRE, TMP1, SLJIT_MEM1(TMP2), sizeof(sljit_sw)) == SLJIT_SUCCESS) { GET_LOCAL_BASE(TMP2, 0, OVECTOR_START + sizeof(sljit_sw)); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, length - 2); loop = LABEL(); sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_STORE | SLJIT_MEM_PRE, TMP1, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); OP2(SLJIT_SUB | SLJIT_SET_Z, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, loop); } else { GET_LOCAL_BASE(TMP2, 0, OVECTOR_START + 2 * sizeof(sljit_sw)); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, length - 2); loop = LABEL(); OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, TMP1, 0); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, sizeof(sljit_sw)); OP2(SLJIT_SUB | SLJIT_SET_Z, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, loop); } } OP1(SLJIT_MOV, STACK_TOP, 0, ARGUMENTS, 0); if (common->mark_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, SLJIT_IMM, 0); if (common->control_head_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), SLJIT_OFFSETOF(jit_arguments, stack)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_ptr); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), SLJIT_OFFSETOF(struct sljit_stack, end)); } static sljit_sw SLJIT_FUNC do_search_mark(sljit_sw *current, const pcre_uchar *skip_arg) { while (current != NULL) { switch (current[1]) { case type_then_trap: break; case type_mark: if (STRCMP_UC_UC(skip_arg, (pcre_uchar *)current[2]) == 0) return current[3]; break; default: SLJIT_UNREACHABLE(); break; } SLJIT_ASSERT(current[0] == 0 || current < (sljit_sw*)current[0]); current = (sljit_sw*)current[0]; } return 0; } static SLJIT_INLINE void copy_ovector(compiler_common *common, int topbracket) { DEFINE_COMPILER; struct sljit_label *loop; struct sljit_jump *early_quit; BOOL has_pre; /* At this point we can freely use all registers. */ OP1(SLJIT_MOV, SLJIT_S2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(1), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_R0, 0, ARGUMENTS, 0); if (common->mark_ptr != 0) OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); OP1(SLJIT_MOV_S32, SLJIT_R1, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, offset_count)); if (common->mark_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, mark_ptr), SLJIT_R2, 0); OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, offsets), SLJIT_IMM, sizeof(int)); OP1(SLJIT_MOV, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, begin)); has_pre = sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_SUPP | SLJIT_MEM_PRE, SLJIT_S1, SLJIT_MEM1(SLJIT_S0), sizeof(sljit_sw)) == SLJIT_SUCCESS; GET_LOCAL_BASE(SLJIT_S0, 0, OVECTOR_START - (has_pre ? sizeof(sljit_sw) : 0)); /* Unlikely, but possible */ early_quit = CMP(SLJIT_EQUAL, SLJIT_R1, 0, SLJIT_IMM, 0); loop = LABEL(); if (has_pre) sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_PRE, SLJIT_S1, SLJIT_MEM1(SLJIT_S0), sizeof(sljit_sw)); else { OP1(SLJIT_MOV, SLJIT_S1, 0, SLJIT_MEM1(SLJIT_S0), 0); OP2(SLJIT_ADD, SLJIT_S0, 0, SLJIT_S0, 0, SLJIT_IMM, sizeof(sljit_sw)); } OP2(SLJIT_ADD, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, sizeof(int)); OP2(SLJIT_SUB, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_R0, 0); /* Copy the integer value to the output buffer */ #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_ASHR, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP1(SLJIT_MOV_S32, SLJIT_MEM1(SLJIT_R2), 0, SLJIT_S1, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, loop); JUMPHERE(early_quit); /* Calculate the return value, which is the maximum ovector value. */ if (topbracket > 1) { if (sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_SUPP | SLJIT_MEM_PRE, SLJIT_R2, SLJIT_MEM1(SLJIT_R0), -(2 * (sljit_sw)sizeof(sljit_sw))) == SLJIT_SUCCESS) { GET_LOCAL_BASE(SLJIT_R0, 0, OVECTOR_START + topbracket * 2 * sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_IMM, topbracket + 1); /* OVECTOR(0) is never equal to SLJIT_S2. */ loop = LABEL(); sljit_emit_mem(compiler, SLJIT_MOV | SLJIT_MEM_PRE, SLJIT_R2, SLJIT_MEM1(SLJIT_R0), -(2 * (sljit_sw)sizeof(sljit_sw))); OP2(SLJIT_SUB, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); CMPTO(SLJIT_EQUAL, SLJIT_R2, 0, SLJIT_S2, 0, loop); } else { GET_LOCAL_BASE(SLJIT_R0, 0, OVECTOR_START + (topbracket - 1) * 2 * sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_IMM, topbracket + 1); /* OVECTOR(0) is never equal to SLJIT_S2. */ loop = LABEL(); OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R0), 0); OP2(SLJIT_SUB, SLJIT_R0, 0, SLJIT_R0, 0, SLJIT_IMM, 2 * (sljit_sw)sizeof(sljit_sw)); OP2(SLJIT_SUB, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); CMPTO(SLJIT_EQUAL, SLJIT_R2, 0, SLJIT_S2, 0, loop); } OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_R1, 0); } else OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1); } static SLJIT_INLINE void return_with_partial_match(compiler_common *common, struct sljit_label *quit) { DEFINE_COMPILER; struct sljit_jump *jump; SLJIT_COMPILE_ASSERT(STR_END == SLJIT_S1, str_end_must_be_saved_reg2); SLJIT_ASSERT(common->start_used_ptr != 0 && common->start_ptr != 0 && (common->mode == JIT_PARTIAL_SOFT_COMPILE ? common->hit_start != 0 : common->hit_start == 0)); OP1(SLJIT_MOV, SLJIT_R1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_PARTIAL); OP1(SLJIT_MOV_S32, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, real_offset_count)); CMPTO(SLJIT_SIG_LESS, SLJIT_R2, 0, SLJIT_IMM, 2, quit); /* Store match begin and end. */ OP1(SLJIT_MOV, SLJIT_S0, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, begin)); OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, offsets)); jump = CMP(SLJIT_SIG_LESS, SLJIT_R2, 0, SLJIT_IMM, 3); OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mode == JIT_PARTIAL_HARD_COMPILE ? common->start_ptr : (common->hit_start + (int)sizeof(sljit_sw)), SLJIT_S0, 0); #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_ASHR, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP1(SLJIT_MOV_S32, SLJIT_MEM1(SLJIT_R1), 2 * sizeof(int), SLJIT_R2, 0); JUMPHERE(jump); OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mode == JIT_PARTIAL_HARD_COMPILE ? common->start_used_ptr : common->hit_start); OP2(SLJIT_SUB, SLJIT_S1, 0, STR_END, 0, SLJIT_S0, 0); #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_ASHR, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP1(SLJIT_MOV_S32, SLJIT_MEM1(SLJIT_R1), sizeof(int), SLJIT_S1, 0); OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_S0, 0); #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_ASHR, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP1(SLJIT_MOV_S32, SLJIT_MEM1(SLJIT_R1), 0, SLJIT_R2, 0); JUMPTO(SLJIT_JUMP, quit); } static SLJIT_INLINE void check_start_used_ptr(compiler_common *common) { /* May destroy TMP1. */ DEFINE_COMPILER; struct sljit_jump *jump; if (common->mode == JIT_PARTIAL_SOFT_COMPILE) { /* The value of -1 must be kept for start_used_ptr! */ OP2(SLJIT_ADD, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, 1); /* Jumps if start_used_ptr < STR_PTR, or start_used_ptr == -1. Although overwriting is not necessary if start_used_ptr == STR_PTR, it does not hurt as well. */ jump = CMP(SLJIT_LESS_EQUAL, TMP1, 0, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); JUMPHERE(jump); } else if (common->mode == JIT_PARTIAL_HARD_COMPILE) { jump = CMP(SLJIT_LESS_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); JUMPHERE(jump); } } static SLJIT_INLINE BOOL char_has_othercase(compiler_common *common, pcre_uchar *cc) { /* Detects if the character has an othercase. */ unsigned int c; #ifdef SUPPORT_UTF if (common->utf) { GETCHAR(c, cc); if (c > 127) { #ifdef SUPPORT_UCP return c != UCD_OTHERCASE(c); #else return FALSE; #endif } #ifndef COMPILE_PCRE8 return common->fcc[c] != c; #endif } else #endif c = *cc; return MAX_255(c) ? common->fcc[c] != c : FALSE; } static SLJIT_INLINE unsigned int char_othercase(compiler_common *common, unsigned int c) { /* Returns with the othercase. */ #ifdef SUPPORT_UTF if (common->utf && c > 127) { #ifdef SUPPORT_UCP return UCD_OTHERCASE(c); #else return c; #endif } #endif return TABLE_GET(c, common->fcc, c); } static unsigned int char_get_othercase_bit(compiler_common *common, pcre_uchar *cc) { /* Detects if the character and its othercase has only 1 bit difference. */ unsigned int c, oc, bit; #if defined SUPPORT_UTF && defined COMPILE_PCRE8 int n; #endif #ifdef SUPPORT_UTF if (common->utf) { GETCHAR(c, cc); if (c <= 127) oc = common->fcc[c]; else { #ifdef SUPPORT_UCP oc = UCD_OTHERCASE(c); #else oc = c; #endif } } else { c = *cc; oc = TABLE_GET(c, common->fcc, c); } #else c = *cc; oc = TABLE_GET(c, common->fcc, c); #endif SLJIT_ASSERT(c != oc); bit = c ^ oc; /* Optimized for English alphabet. */ if (c <= 127 && bit == 0x20) return (0 << 8) | 0x20; /* Since c != oc, they must have at least 1 bit difference. */ if (!is_powerof2(bit)) return 0; #if defined COMPILE_PCRE8 #ifdef SUPPORT_UTF if (common->utf && c > 127) { n = GET_EXTRALEN(*cc); while ((bit & 0x3f) == 0) { n--; bit >>= 6; } return (n << 8) | bit; } #endif /* SUPPORT_UTF */ return (0 << 8) | bit; #elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 #ifdef SUPPORT_UTF if (common->utf && c > 65535) { if (bit >= (1 << 10)) bit >>= 10; else return (bit < 256) ? ((2 << 8) | bit) : ((3 << 8) | (bit >> 8)); } #endif /* SUPPORT_UTF */ return (bit < 256) ? ((0 << 8) | bit) : ((1 << 8) | (bit >> 8)); #endif /* COMPILE_PCRE[8|16|32] */ } static void check_partial(compiler_common *common, BOOL force) { /* Checks whether a partial matching is occurred. Does not modify registers. */ DEFINE_COMPILER; struct sljit_jump *jump = NULL; SLJIT_ASSERT(!force || common->mode != JIT_COMPILE); if (common->mode == JIT_COMPILE) return; if (!force) jump = CMP(SLJIT_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); else if (common->mode == JIT_PARTIAL_SOFT_COMPILE) jump = CMP(SLJIT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, -1); if (common->mode == JIT_PARTIAL_SOFT_COMPILE) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); else { if (common->partialmatchlabel != NULL) JUMPTO(SLJIT_JUMP, common->partialmatchlabel); else add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); } if (jump != NULL) JUMPHERE(jump); } static void check_str_end(compiler_common *common, jump_list **end_reached) { /* Does not affect registers. Usually used in a tight spot. */ DEFINE_COMPILER; struct sljit_jump *jump; if (common->mode == JIT_COMPILE) { add_jump(compiler, end_reached, CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); return; } jump = CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0); if (common->mode == JIT_PARTIAL_SOFT_COMPILE) { add_jump(compiler, end_reached, CMP(SLJIT_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); add_jump(compiler, end_reached, JUMP(SLJIT_JUMP)); } else { add_jump(compiler, end_reached, CMP(SLJIT_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); if (common->partialmatchlabel != NULL) JUMPTO(SLJIT_JUMP, common->partialmatchlabel); else add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); } JUMPHERE(jump); } static void detect_partial_match(compiler_common *common, jump_list **backtracks) { DEFINE_COMPILER; struct sljit_jump *jump; if (common->mode == JIT_COMPILE) { add_jump(compiler, backtracks, CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); return; } /* Partial matching mode. */ jump = CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0); add_jump(compiler, backtracks, CMP(SLJIT_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); if (common->mode == JIT_PARTIAL_SOFT_COMPILE) { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); } else { if (common->partialmatchlabel != NULL) JUMPTO(SLJIT_JUMP, common->partialmatchlabel); else add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); } JUMPHERE(jump); } static void peek_char(compiler_common *common, sljit_u32 max) { /* Reads the character into TMP1, keeps STR_PTR. Does not check STR_END. TMP2 Destroyed. */ DEFINE_COMPILER; #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 struct sljit_jump *jump; #endif SLJIT_UNUSED_ARG(max); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf) { if (max < 128) return; jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); add_jump(compiler, &common->utfreadchar, JUMP(SLJIT_FAST_CALL)); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); JUMPHERE(jump); } #endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ #if defined SUPPORT_UTF && defined COMPILE_PCRE16 if (common->utf) { if (max < 0xd800) return; OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); jump = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); /* TMP2 contains the high surrogate. */ OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x40); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 10); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3ff); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); JUMPHERE(jump); } #endif } #if defined SUPPORT_UTF && defined COMPILE_PCRE8 static BOOL is_char7_bitset(const sljit_u8 *bitset, BOOL nclass) { /* Tells whether the character codes below 128 are enough to determine a match. */ const sljit_u8 value = nclass ? 0xff : 0; const sljit_u8 *end = bitset + 32; bitset += 16; do { if (*bitset++ != value) return FALSE; } while (bitset < end); return TRUE; } static void read_char7_type(compiler_common *common, BOOL full_read) { /* Reads the precise character type of a character into TMP1, if the character is less than 128. Otherwise it returns with zero. Does not check STR_END. The full_read argument tells whether characters above max are accepted or not. */ DEFINE_COMPILER; struct sljit_jump *jump; SLJIT_ASSERT(common->utf); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); if (full_read) { jump = CMP(SLJIT_LESS, TMP2, 0, SLJIT_IMM, 0xc0); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); JUMPHERE(jump); } } #endif /* SUPPORT_UTF && COMPILE_PCRE8 */ static void read_char_range(compiler_common *common, sljit_u32 min, sljit_u32 max, BOOL update_str_ptr) { /* Reads the precise value of a character into TMP1, if the character is between min and max (c >= min && c <= max). Otherwise it returns with a value outside the range. Does not check STR_END. */ DEFINE_COMPILER; #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 struct sljit_jump *jump; #endif #if defined SUPPORT_UTF && defined COMPILE_PCRE8 struct sljit_jump *jump2; #endif SLJIT_UNUSED_ARG(update_str_ptr); SLJIT_UNUSED_ARG(min); SLJIT_UNUSED_ARG(max); SLJIT_ASSERT(min <= max); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf) { if (max < 128 && !update_str_ptr) return; jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xc0); if (min >= 0x10000) { OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xf0); if (update_str_ptr) OP1(SLJIT_MOV_U8, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); jump2 = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0x7); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(2)); if (!update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(3)); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); JUMPHERE(jump2); if (update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); } else if (min >= 0x800 && max <= 0xffff) { OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xe0); if (update_str_ptr) OP1(SLJIT_MOV_U8, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); jump2 = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0xf); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); if (!update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); JUMPHERE(jump2); if (update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); } else if (max >= 0x800) add_jump(compiler, (max < 0x10000) ? &common->utfreadchar16 : &common->utfreadchar, JUMP(SLJIT_FAST_CALL)); else if (max < 128) { OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); } else { OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); if (!update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); else OP1(SLJIT_MOV_U8, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); if (update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); } JUMPHERE(jump); } #endif #if defined SUPPORT_UTF && defined COMPILE_PCRE16 if (common->utf) { if (max >= 0x10000) { OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); jump = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); /* TMP2 contains the high surrogate. */ OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x40); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 10); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3ff); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); JUMPHERE(jump); return; } if (max < 0xd800 && !update_str_ptr) return; /* Skip low surrogate if necessary. */ OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); jump = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); if (update_str_ptr) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); if (max >= 0xd800) OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0x10000); JUMPHERE(jump); } #endif } static SLJIT_INLINE void read_char(compiler_common *common) { read_char_range(common, 0, READ_CHAR_MAX, TRUE); } static void read_char8_type(compiler_common *common, BOOL update_str_ptr) { /* Reads the character type into TMP1, updates STR_PTR. Does not check STR_END. */ DEFINE_COMPILER; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 struct sljit_jump *jump; #endif #if defined SUPPORT_UTF && defined COMPILE_PCRE8 struct sljit_jump *jump2; #endif SLJIT_UNUSED_ARG(update_str_ptr); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf) { /* This can be an extra read in some situations, but hopefully it is needed in most cases. */ OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); jump = CMP(SLJIT_LESS, TMP2, 0, SLJIT_IMM, 0xc0); if (!update_str_ptr) { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP2, 0, TMP2, 0, TMP1, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); jump2 = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 255); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); JUMPHERE(jump2); } else add_jump(compiler, &common->utfreadtype8, JUMP(SLJIT_FAST_CALL)); JUMPHERE(jump); return; } #endif /* SUPPORT_UTF && COMPILE_PCRE8 */ #if !defined COMPILE_PCRE8 /* The ctypes array contains only 256 values. */ OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); jump = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 255); #endif OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); #if !defined COMPILE_PCRE8 JUMPHERE(jump); #endif #if defined SUPPORT_UTF && defined COMPILE_PCRE16 if (common->utf && update_str_ptr) { /* Skip low surrogate if necessary. */ OP2(SLJIT_SUB, TMP2, 0, TMP2, 0, SLJIT_IMM, 0xd800); jump = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPHERE(jump); } #endif /* SUPPORT_UTF && COMPILE_PCRE16 */ } static void skip_char_back(compiler_common *common) { /* Goes one character back. Affects STR_PTR and TMP1. Does not check begin. */ DEFINE_COMPILER; #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 #if defined COMPILE_PCRE8 struct sljit_label *label; if (common->utf) { label = LABEL(); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1)); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, label); return; } #elif defined COMPILE_PCRE16 if (common->utf) { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1)); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); /* Skip low surrogate if necessary. */ OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xdc00); OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP1, 0); return; } #endif /* COMPILE_PCRE[8|16] */ #endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } static void check_newlinechar(compiler_common *common, int nltype, jump_list **backtracks, BOOL jumpifmatch) { /* Character comes in TMP1. Checks if it is a newline. TMP2 may be destroyed. */ DEFINE_COMPILER; struct sljit_jump *jump; if (nltype == NLTYPE_ANY) { add_jump(compiler, &common->anynewline, JUMP(SLJIT_FAST_CALL)); sljit_set_current_flags(compiler, SLJIT_SET_Z); add_jump(compiler, backtracks, JUMP(jumpifmatch ? SLJIT_NOT_ZERO : SLJIT_ZERO)); } else if (nltype == NLTYPE_ANYCRLF) { if (jumpifmatch) { add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR)); add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); } else { jump = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); JUMPHERE(jump); } } else { SLJIT_ASSERT(nltype == NLTYPE_FIXED && common->newline < 256); add_jump(compiler, backtracks, CMP(jumpifmatch ? SLJIT_EQUAL : SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline)); } } #ifdef SUPPORT_UTF #if defined COMPILE_PCRE8 static void do_utfreadchar(compiler_common *common) { /* Fast decoding a UTF-8 character. TMP1 contains the first byte of the character (>= 0xc0). Return char value in TMP1, length in TMP2. */ DEFINE_COMPILER; struct sljit_jump *jump; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); /* Searching for the first zero. */ OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x800); jump = JUMP(SLJIT_NOT_ZERO); /* Two byte sequence. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(2)); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); JUMPHERE(jump); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x800); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x10000); jump = JUMP(SLJIT_NOT_ZERO); /* Three byte sequence. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(3)); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); /* Four byte sequence. */ JUMPHERE(jump); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(2)); OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x10000); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(3)); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(4)); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } static void do_utfreadchar16(compiler_common *common) { /* Fast decoding a UTF-8 character. TMP1 contains the first byte of the character (>= 0xc0). Return value in TMP1. */ DEFINE_COMPILER; struct sljit_jump *jump; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); /* Searching for the first zero. */ OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x800); jump = JUMP(SLJIT_NOT_ZERO); /* Two byte sequence. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); JUMPHERE(jump); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x400); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_NOT_ZERO); /* This code runs only in 8 bit mode. No need to shift the value. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x800); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); /* Three byte sequence. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } static void do_utfreadtype8(compiler_common *common) { /* Fast decoding a UTF-8 character type. TMP2 contains the first byte of the character (>= 0xc0). Return value in TMP1. */ DEFINE_COMPILER; struct sljit_jump *jump; struct sljit_jump *compare; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, 0x20); jump = JUMP(SLJIT_NOT_ZERO); /* Two byte sequence. */ OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x1f); /* The upper 5 bits are known at this point. */ compare = CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, 0x3); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); OP2(SLJIT_OR, TMP2, 0, TMP2, 0, TMP1, 0); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); JUMPHERE(compare); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); /* We only have types for characters less than 256. */ JUMPHERE(jump); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } #endif /* COMPILE_PCRE8 */ #endif /* SUPPORT_UTF */ #ifdef SUPPORT_UCP /* UCD_BLOCK_SIZE must be 128 (see the assert below). */ #define UCD_BLOCK_MASK 127 #define UCD_BLOCK_SHIFT 7 static void do_getucd(compiler_common *common) { /* Search the UCD record for the character comes in TMP1. Returns chartype in TMP1 and UCD offset in TMP2. */ DEFINE_COMPILER; #ifdef COMPILE_PCRE32 struct sljit_jump *jump; #endif #if defined SLJIT_DEBUG && SLJIT_DEBUG /* dummy_ucd_record */ const ucd_record *record = GET_UCD(INVALID_UTF_CHAR); SLJIT_ASSERT(record->script == ucp_Common && record->chartype == ucp_Cn && record->gbprop == ucp_gbOther); SLJIT_ASSERT(record->caseset == 0 && record->other_case == 0); #endif SLJIT_ASSERT(UCD_BLOCK_SIZE == 128 && sizeof(ucd_record) == 8); sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); #ifdef COMPILE_PCRE32 if (!common->utf) { jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0x10ffff + 1); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, INVALID_UTF_CHAR); JUMPHERE(jump); } #endif OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2)); OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype)); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM2(TMP1, TMP2), 3); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } #endif static SLJIT_INLINE struct sljit_label *mainloop_entry(compiler_common *common, BOOL hascrorlf) { DEFINE_COMPILER; struct sljit_label *mainloop; struct sljit_label *newlinelabel = NULL; struct sljit_jump *start; struct sljit_jump *end = NULL; struct sljit_jump *end2 = NULL; #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 struct sljit_jump *singlechar; #endif jump_list *newline = NULL; BOOL newlinecheck = FALSE; BOOL readuchar = FALSE; if (!(hascrorlf || (common->match_end_ptr != 0)) && (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF || common->newline > 255)) newlinecheck = TRUE; if (common->match_end_ptr != 0) { /* Search for the end of the first line. */ OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); if (common->nltype == NLTYPE_FIXED && common->newline > 255) { mainloop = LABEL(); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); end = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, mainloop); CMPTO(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff, mainloop); JUMPHERE(end); OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } else { end = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); mainloop = LABEL(); /* Continual stores does not cause data dependency. */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr, STR_PTR, 0); read_char_range(common, common->nlmin, common->nlmax, TRUE); check_newlinechar(common, common->nltype, &newline, TRUE); CMPTO(SLJIT_LESS, STR_PTR, 0, STR_END, 0, mainloop); JUMPHERE(end); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr, STR_PTR, 0); set_jumps(newline, LABEL()); } OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); } start = JUMP(SLJIT_JUMP); if (newlinecheck) { newlinelabel = LABEL(); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); end = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, common->newline & 0xff); OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL); #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); end2 = JUMP(SLJIT_JUMP); } mainloop = LABEL(); /* Increasing the STR_PTR here requires one less jump in the most common case. */ #ifdef SUPPORT_UTF if (common->utf) readuchar = TRUE; #endif if (newlinecheck) readuchar = TRUE; if (readuchar) OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); if (newlinecheck) CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, newlinelabel); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 #if defined COMPILE_PCRE8 if (common->utf) { singlechar = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xc0); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); JUMPHERE(singlechar); } #elif defined COMPILE_PCRE16 if (common->utf) { singlechar = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xd800); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); JUMPHERE(singlechar); } #endif /* COMPILE_PCRE[8|16] */ #endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ JUMPHERE(start); if (newlinecheck) { JUMPHERE(end); JUMPHERE(end2); } return mainloop; } #define MAX_N_CHARS 16 #define MAX_DIFF_CHARS 6 static SLJIT_INLINE void add_prefix_char(pcre_uchar chr, pcre_uchar *chars) { pcre_uchar i, len; len = chars[0]; if (len == 255) return; if (len == 0) { chars[0] = 1; chars[1] = chr; return; } for (i = len; i > 0; i--) if (chars[i] == chr) return; if (len >= MAX_DIFF_CHARS - 1) { chars[0] = 255; return; } len++; chars[len] = chr; chars[0] = len; } static int scan_prefix(compiler_common *common, pcre_uchar *cc, pcre_uchar *chars, int max_chars, sljit_u32 *rec_count) { /* Recursive function, which scans prefix literals. */ BOOL last, any, class, caseless; int len, repeat, len_save, consumed = 0; sljit_u32 chr; /* Any unicode character. */ sljit_u8 *bytes, *bytes_end, byte; pcre_uchar *alternative, *cc_save, *oc; #if defined SUPPORT_UTF && defined COMPILE_PCRE8 pcre_uchar othercase[8]; #elif defined SUPPORT_UTF && defined COMPILE_PCRE16 pcre_uchar othercase[2]; #else pcre_uchar othercase[1]; #endif repeat = 1; while (TRUE) { if (*rec_count == 0) return 0; (*rec_count)--; last = TRUE; any = FALSE; class = FALSE; caseless = FALSE; switch (*cc) { case OP_CHARI: caseless = TRUE; case OP_CHAR: last = FALSE; cc++; break; case OP_SOD: case OP_SOM: case OP_SET_SOM: case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_EODN: case OP_EOD: case OP_CIRC: case OP_CIRCM: case OP_DOLL: case OP_DOLLM: /* Zero width assertions. */ cc++; continue; case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: cc = bracketend(cc); continue; case OP_PLUSI: case OP_MINPLUSI: case OP_POSPLUSI: caseless = TRUE; case OP_PLUS: case OP_MINPLUS: case OP_POSPLUS: cc++; break; case OP_EXACTI: caseless = TRUE; case OP_EXACT: repeat = GET2(cc, 1); last = FALSE; cc += 1 + IMM2_SIZE; break; case OP_QUERYI: case OP_MINQUERYI: case OP_POSQUERYI: caseless = TRUE; case OP_QUERY: case OP_MINQUERY: case OP_POSQUERY: len = 1; cc++; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(*cc)) len += GET_EXTRALEN(*cc); #endif max_chars = scan_prefix(common, cc + len, chars, max_chars, rec_count); if (max_chars == 0) return consumed; last = FALSE; break; case OP_KET: cc += 1 + LINK_SIZE; continue; case OP_ALT: cc += GET(cc, 1); continue; case OP_ONCE: case OP_ONCE_NC: case OP_BRA: case OP_BRAPOS: case OP_CBRA: case OP_CBRAPOS: alternative = cc + GET(cc, 1); while (*alternative == OP_ALT) { max_chars = scan_prefix(common, alternative + 1 + LINK_SIZE, chars, max_chars, rec_count); if (max_chars == 0) return consumed; alternative += GET(alternative, 1); } if (*cc == OP_CBRA || *cc == OP_CBRAPOS) cc += IMM2_SIZE; cc += 1 + LINK_SIZE; continue; case OP_CLASS: #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && !is_char7_bitset((const sljit_u8 *)(cc + 1), FALSE)) return consumed; #endif class = TRUE; break; case OP_NCLASS: #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf) return consumed; #endif class = TRUE; break; #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf) return consumed; #endif any = TRUE; cc += GET(cc, 1); break; #endif case OP_DIGIT: #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && !is_char7_bitset((const sljit_u8 *)common->ctypes - cbit_length + cbit_digit, FALSE)) return consumed; #endif any = TRUE; cc++; break; case OP_WHITESPACE: #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && !is_char7_bitset((const sljit_u8 *)common->ctypes - cbit_length + cbit_space, FALSE)) return consumed; #endif any = TRUE; cc++; break; case OP_WORDCHAR: #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && !is_char7_bitset((const sljit_u8 *)common->ctypes - cbit_length + cbit_word, FALSE)) return consumed; #endif any = TRUE; cc++; break; case OP_NOT: case OP_NOTI: cc++; /* Fall through. */ case OP_NOT_DIGIT: case OP_NOT_WHITESPACE: case OP_NOT_WORDCHAR: case OP_ANY: case OP_ALLANY: #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf) return consumed; #endif any = TRUE; cc++; break; #ifdef SUPPORT_UTF case OP_NOTPROP: case OP_PROP: #ifndef COMPILE_PCRE32 if (common->utf) return consumed; #endif any = TRUE; cc += 1 + 2; break; #endif case OP_TYPEEXACT: repeat = GET2(cc, 1); cc += 1 + IMM2_SIZE; continue; case OP_NOTEXACT: case OP_NOTEXACTI: #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf) return consumed; #endif any = TRUE; repeat = GET2(cc, 1); cc += 1 + IMM2_SIZE + 1; break; default: return consumed; } if (any) { do { chars[0] = 255; consumed++; if (--max_chars == 0) return consumed; chars += MAX_DIFF_CHARS; } while (--repeat > 0); repeat = 1; continue; } if (class) { bytes = (sljit_u8*) (cc + 1); cc += 1 + 32 / sizeof(pcre_uchar); switch (*cc) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPOSSTAR: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSQUERY: max_chars = scan_prefix(common, cc + 1, chars, max_chars, rec_count); if (max_chars == 0) return consumed; break; default: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRPOSPLUS: break; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: repeat = GET2(cc, 1); if (repeat <= 0) return consumed; break; } do { if (bytes[31] & 0x80) chars[0] = 255; else if (chars[0] != 255) { bytes_end = bytes + 32; chr = 0; do { byte = *bytes++; SLJIT_ASSERT((chr & 0x7) == 0); if (byte == 0) chr += 8; else { do { if ((byte & 0x1) != 0) add_prefix_char(chr, chars); byte >>= 1; chr++; } while (byte != 0); chr = (chr + 7) & ~7; } } while (chars[0] != 255 && bytes < bytes_end); bytes = bytes_end - 32; } consumed++; if (--max_chars == 0) return consumed; chars += MAX_DIFF_CHARS; } while (--repeat > 0); switch (*cc) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPOSSTAR: return consumed; case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSQUERY: cc++; break; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: if (GET2(cc, 1) != GET2(cc, 1 + IMM2_SIZE)) return consumed; cc += 1 + 2 * IMM2_SIZE; break; } repeat = 1; continue; } len = 1; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(*cc)) len += GET_EXTRALEN(*cc); #endif if (caseless && char_has_othercase(common, cc)) { #ifdef SUPPORT_UTF if (common->utf) { GETCHAR(chr, cc); if ((int)PRIV(ord2utf)(char_othercase(common, chr), othercase) != len) return consumed; } else #endif { chr = *cc; othercase[0] = TABLE_GET(chr, common->fcc, chr); } } else { caseless = FALSE; othercase[0] = 0; /* Stops compiler warning - PH */ } len_save = len; cc_save = cc; while (TRUE) { oc = othercase; do { chr = *cc; add_prefix_char(*cc, chars); if (caseless) add_prefix_char(*oc, chars); len--; consumed++; if (--max_chars == 0) return consumed; chars += MAX_DIFF_CHARS; cc++; oc++; } while (len > 0); if (--repeat == 0) break; len = len_save; cc = cc_save; } repeat = 1; if (last) return consumed; } } #if (defined SLJIT_CONFIG_X86 && SLJIT_CONFIG_X86) && !(defined SUPPORT_VALGRIND) static sljit_s32 character_to_int32(pcre_uchar chr) { sljit_s32 value = (sljit_s32)chr; #if defined COMPILE_PCRE8 #define SSE2_COMPARE_TYPE_INDEX 0 return ((unsigned int)value << 24) | ((unsigned int)value << 16) | ((unsigned int)value << 8) | (unsigned int)value; #elif defined COMPILE_PCRE16 #define SSE2_COMPARE_TYPE_INDEX 1 return ((unsigned int)value << 16) | value; #elif defined COMPILE_PCRE32 #define SSE2_COMPARE_TYPE_INDEX 2 return value; #else #error "Unsupported unit width" #endif } static SLJIT_INLINE void fast_forward_first_char2_sse2(compiler_common *common, pcre_uchar char1, pcre_uchar char2) { DEFINE_COMPILER; struct sljit_label *start; struct sljit_jump *quit[3]; struct sljit_jump *nomatch; sljit_u8 instruction[8]; sljit_s32 tmp1_ind = sljit_get_register_index(TMP1); sljit_s32 tmp2_ind = sljit_get_register_index(TMP2); sljit_s32 str_ptr_ind = sljit_get_register_index(STR_PTR); BOOL load_twice = FALSE; pcre_uchar bit; bit = char1 ^ char2; if (!is_powerof2(bit)) bit = 0; if ((char1 != char2) && bit == 0) load_twice = TRUE; quit[0] = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); /* First part (unaligned start) */ OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, character_to_int32(char1 | bit)); SLJIT_ASSERT(tmp1_ind < 8 && tmp2_ind == 1); /* MOVD xmm, r/m32 */ instruction[0] = 0x66; instruction[1] = 0x0f; instruction[2] = 0x6e; instruction[3] = 0xc0 | (2 << 3) | tmp1_ind; sljit_emit_op_custom(compiler, instruction, 4); if (char1 != char2) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, character_to_int32(bit != 0 ? bit : char2)); /* MOVD xmm, r/m32 */ instruction[3] = 0xc0 | (3 << 3) | tmp1_ind; sljit_emit_op_custom(compiler, instruction, 4); } /* PSHUFD xmm1, xmm2/m128, imm8 */ instruction[2] = 0x70; instruction[3] = 0xc0 | (2 << 3) | 2; instruction[4] = 0; sljit_emit_op_custom(compiler, instruction, 5); if (char1 != char2) { /* PSHUFD xmm1, xmm2/m128, imm8 */ instruction[3] = 0xc0 | (3 << 3) | 3; instruction[4] = 0; sljit_emit_op_custom(compiler, instruction, 5); } OP2(SLJIT_AND, TMP2, 0, STR_PTR, 0, SLJIT_IMM, 0xf); OP2(SLJIT_AND, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, ~0xf); /* MOVDQA xmm1, xmm2/m128 */ #if (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) if (str_ptr_ind < 8) { instruction[2] = 0x6f; instruction[3] = (0 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = (1 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); } } else { instruction[1] = 0x41; instruction[2] = 0x0f; instruction[3] = 0x6f; instruction[4] = (0 << 3) | (str_ptr_ind & 0x7); sljit_emit_op_custom(compiler, instruction, 5); if (load_twice) { instruction[4] = (1 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 5); } instruction[1] = 0x0f; } #else instruction[2] = 0x6f; instruction[3] = (0 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = (1 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); } #endif if (bit != 0) { /* POR xmm1, xmm2/m128 */ instruction[2] = 0xeb; instruction[3] = 0xc0 | (0 << 3) | 3; sljit_emit_op_custom(compiler, instruction, 4); } /* PCMPEQB/W/D xmm1, xmm2/m128 */ instruction[2] = 0x74 + SSE2_COMPARE_TYPE_INDEX; instruction[3] = 0xc0 | (0 << 3) | 2; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = 0xc0 | (1 << 3) | 3; sljit_emit_op_custom(compiler, instruction, 4); } /* PMOVMSKB reg, xmm */ instruction[2] = 0xd7; instruction[3] = 0xc0 | (tmp1_ind << 3) | 0; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP2, 0); instruction[3] = 0xc0 | (tmp2_ind << 3) | 1; sljit_emit_op_custom(compiler, instruction, 4); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); OP1(SLJIT_MOV, TMP2, 0, RETURN_ADDR, 0); } OP2(SLJIT_ASHR, TMP1, 0, TMP1, 0, TMP2, 0); /* BSF r32, r/m32 */ instruction[0] = 0x0f; instruction[1] = 0xbc; instruction[2] = 0xc0 | (tmp1_ind << 3) | tmp1_ind; sljit_emit_op_custom(compiler, instruction, 3); sljit_set_current_flags(compiler, SLJIT_SET_Z); nomatch = JUMP(SLJIT_ZERO); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); quit[1] = JUMP(SLJIT_JUMP); JUMPHERE(nomatch); start = LABEL(); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, 16); quit[2] = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); /* Second part (aligned) */ instruction[0] = 0x66; instruction[1] = 0x0f; /* MOVDQA xmm1, xmm2/m128 */ #if (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64) if (str_ptr_ind < 8) { instruction[2] = 0x6f; instruction[3] = (0 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = (1 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); } } else { instruction[1] = 0x41; instruction[2] = 0x0f; instruction[3] = 0x6f; instruction[4] = (0 << 3) | (str_ptr_ind & 0x7); sljit_emit_op_custom(compiler, instruction, 5); if (load_twice) { instruction[4] = (1 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 5); } instruction[1] = 0x0f; } #else instruction[2] = 0x6f; instruction[3] = (0 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = (1 << 3) | str_ptr_ind; sljit_emit_op_custom(compiler, instruction, 4); } #endif if (bit != 0) { /* POR xmm1, xmm2/m128 */ instruction[2] = 0xeb; instruction[3] = 0xc0 | (0 << 3) | 3; sljit_emit_op_custom(compiler, instruction, 4); } /* PCMPEQB/W/D xmm1, xmm2/m128 */ instruction[2] = 0x74 + SSE2_COMPARE_TYPE_INDEX; instruction[3] = 0xc0 | (0 << 3) | 2; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = 0xc0 | (1 << 3) | 3; sljit_emit_op_custom(compiler, instruction, 4); } /* PMOVMSKB reg, xmm */ instruction[2] = 0xd7; instruction[3] = 0xc0 | (tmp1_ind << 3) | 0; sljit_emit_op_custom(compiler, instruction, 4); if (load_twice) { instruction[3] = 0xc0 | (tmp2_ind << 3) | 1; sljit_emit_op_custom(compiler, instruction, 4); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); } /* BSF r32, r/m32 */ instruction[0] = 0x0f; instruction[1] = 0xbc; instruction[2] = 0xc0 | (tmp1_ind << 3) | tmp1_ind; sljit_emit_op_custom(compiler, instruction, 3); sljit_set_current_flags(compiler, SLJIT_SET_Z); JUMPTO(SLJIT_ZERO, start); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); start = LABEL(); SET_LABEL(quit[0], start); SET_LABEL(quit[1], start); SET_LABEL(quit[2], start); } #undef SSE2_COMPARE_TYPE_INDEX #endif static void fast_forward_first_char2(compiler_common *common, pcre_uchar char1, pcre_uchar char2, sljit_s32 offset) { DEFINE_COMPILER; struct sljit_label *start; struct sljit_jump *quit; struct sljit_jump *found; pcre_uchar mask; #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 struct sljit_label *utf_start = NULL; struct sljit_jump *utf_quit = NULL; #endif BOOL has_match_end = (common->match_end_ptr != 0); if (offset > 0) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(offset)); if (has_match_end) { OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); OP2(SLJIT_ADD, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr, SLJIT_IMM, IN_UCHARS(offset + 1)); OP2(SLJIT_SUB | SLJIT_SET_GREATER, SLJIT_UNUSED, 0, STR_END, 0, TMP3, 0); sljit_emit_cmov(compiler, SLJIT_GREATER, STR_END, TMP3, 0); } #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf && offset > 0) utf_start = LABEL(); #endif #if (defined SLJIT_CONFIG_X86 && SLJIT_CONFIG_X86) && !(defined SUPPORT_VALGRIND) /* SSE2 accelerated first character search. */ if (sljit_has_cpu_feature(SLJIT_HAS_SSE2)) { fast_forward_first_char2_sse2(common, char1, char2); SLJIT_ASSERT(common->mode == JIT_COMPILE || offset == 0); if (common->mode == JIT_COMPILE) { /* In complete mode, we don't need to run a match when STR_PTR == STR_END. */ SLJIT_ASSERT(common->forced_quit_label == NULL); OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); add_jump(compiler, &common->forced_quit, CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf && offset > 0) { SLJIT_ASSERT(common->mode == JIT_COMPILE); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-offset)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #if defined COMPILE_PCRE8 OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, utf_start); #elif defined COMPILE_PCRE16 OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0xdc00, utf_start); #else #error "Unknown code width" #endif OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } #endif if (offset > 0) OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(offset)); } else { OP2(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, SLJIT_UNUSED, 0, STR_PTR, 0, STR_END, 0); if (has_match_end) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); sljit_emit_cmov(compiler, SLJIT_GREATER_EQUAL, STR_PTR, TMP1, 0); } else sljit_emit_cmov(compiler, SLJIT_GREATER_EQUAL, STR_PTR, STR_END, 0); } if (has_match_end) OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); return; } #endif quit = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); start = LABEL(); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); if (char1 == char2) found = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, char1); else { mask = char1 ^ char2; if (is_powerof2(mask)) { OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, mask); found = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, char1 | mask); } else { OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, char1); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, char2); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); found = JUMP(SLJIT_NOT_ZERO); } } OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); CMPTO(SLJIT_LESS, STR_PTR, 0, STR_END, 0, start); #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf && offset > 0) utf_quit = JUMP(SLJIT_JUMP); #endif JUMPHERE(found); #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf && offset > 0) { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-offset)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #if defined COMPILE_PCRE8 OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, utf_start); #elif defined COMPILE_PCRE16 OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0xdc00, utf_start); #else #error "Unknown code width" #endif OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPHERE(utf_quit); } #endif JUMPHERE(quit); if (has_match_end) { quit = CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); if (offset > 0) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(offset)); JUMPHERE(quit); OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); } if (offset > 0) OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(offset)); } static SLJIT_INLINE BOOL fast_forward_first_n_chars(compiler_common *common) { DEFINE_COMPILER; struct sljit_label *start; struct sljit_jump *quit; struct sljit_jump *match; /* bytes[0] represent the number of characters between 0 and MAX_N_BYTES - 1, 255 represents any character. */ pcre_uchar chars[MAX_N_CHARS * MAX_DIFF_CHARS]; sljit_s32 offset; pcre_uchar mask; pcre_uchar *char_set, *char_set_end; int i, max, from; int range_right = -1, range_len; sljit_u8 *update_table = NULL; BOOL in_range; sljit_u32 rec_count; for (i = 0; i < MAX_N_CHARS; i++) chars[i * MAX_DIFF_CHARS] = 0; rec_count = 10000; max = scan_prefix(common, common->start, chars, MAX_N_CHARS, &rec_count); if (max < 1) return FALSE; in_range = FALSE; /* Prevent compiler "uninitialized" warning */ from = 0; range_len = 4 /* minimum length */ - 1; for (i = 0; i <= max; i++) { if (in_range && (i - from) > range_len && (chars[(i - 1) * MAX_DIFF_CHARS] < 255)) { range_len = i - from; range_right = i - 1; } if (i < max && chars[i * MAX_DIFF_CHARS] < 255) { SLJIT_ASSERT(chars[i * MAX_DIFF_CHARS] > 0); if (!in_range) { in_range = TRUE; from = i; } } else in_range = FALSE; } if (range_right >= 0) { update_table = (sljit_u8 *)allocate_read_only_data(common, 256); if (update_table == NULL) return TRUE; memset(update_table, IN_UCHARS(range_len), 256); for (i = 0; i < range_len; i++) { char_set = chars + ((range_right - i) * MAX_DIFF_CHARS); SLJIT_ASSERT(char_set[0] > 0 && char_set[0] < 255); char_set_end = char_set + char_set[0]; char_set++; while (char_set <= char_set_end) { if (update_table[(*char_set) & 0xff] > IN_UCHARS(i)) update_table[(*char_set) & 0xff] = IN_UCHARS(i); char_set++; } } } offset = -1; /* Scan forward. */ for (i = 0; i < max; i++) { if (offset == -1) { if (chars[i * MAX_DIFF_CHARS] <= 2) offset = i; } else if (chars[offset * MAX_DIFF_CHARS] == 2 && chars[i * MAX_DIFF_CHARS] <= 2) { if (chars[i * MAX_DIFF_CHARS] == 1) offset = i; else { mask = chars[offset * MAX_DIFF_CHARS + 1] ^ chars[offset * MAX_DIFF_CHARS + 2]; if (!is_powerof2(mask)) { mask = chars[i * MAX_DIFF_CHARS + 1] ^ chars[i * MAX_DIFF_CHARS + 2]; if (is_powerof2(mask)) offset = i; } } } } if (range_right < 0) { if (offset < 0) return FALSE; SLJIT_ASSERT(chars[offset * MAX_DIFF_CHARS] >= 1 && chars[offset * MAX_DIFF_CHARS] <= 2); /* Works regardless the value is 1 or 2. */ mask = chars[offset * MAX_DIFF_CHARS + chars[offset * MAX_DIFF_CHARS]]; fast_forward_first_char2(common, chars[offset * MAX_DIFF_CHARS + 1], mask, offset); return TRUE; } if (range_right == offset) offset = -1; SLJIT_ASSERT(offset == -1 || (chars[offset * MAX_DIFF_CHARS] >= 1 && chars[offset * MAX_DIFF_CHARS] <= 2)); max -= 1; SLJIT_ASSERT(max > 0); if (common->match_end_ptr != 0) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); OP2(SLJIT_SUB, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); quit = CMP(SLJIT_LESS_EQUAL, STR_END, 0, TMP1, 0); OP1(SLJIT_MOV, STR_END, 0, TMP1, 0); JUMPHERE(quit); } else OP2(SLJIT_SUB, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); SLJIT_ASSERT(range_right >= 0); #if !(defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) OP1(SLJIT_MOV, RETURN_ADDR, 0, SLJIT_IMM, (sljit_sw)update_table); #endif start = LABEL(); quit = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); #if defined COMPILE_PCRE8 || (defined SLJIT_LITTLE_ENDIAN && SLJIT_LITTLE_ENDIAN) OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(range_right)); #else OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(range_right + 1) - 1); #endif #if !(defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM2(RETURN_ADDR, TMP1), 0); #else OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)update_table); #endif OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, start); if (offset >= 0) { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offset)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); if (chars[offset * MAX_DIFF_CHARS] == 1) CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[offset * MAX_DIFF_CHARS + 1], start); else { mask = chars[offset * MAX_DIFF_CHARS + 1] ^ chars[offset * MAX_DIFF_CHARS + 2]; if (is_powerof2(mask)) { OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, mask); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[offset * MAX_DIFF_CHARS + 1] | mask, start); } else { match = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, chars[offset * MAX_DIFF_CHARS + 1]); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[offset * MAX_DIFF_CHARS + 2], start); JUMPHERE(match); } } } #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf && offset != 0) { if (offset < 0) { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } else OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); #if defined COMPILE_PCRE8 OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, start); #elif defined COMPILE_PCRE16 OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0xdc00, start); #else #error "Unknown code width" #endif if (offset < 0) OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } #endif if (offset >= 0) OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPHERE(quit); if (common->match_end_ptr != 0) { if (range_right >= 0) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); if (range_right >= 0) { quit = CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, TMP1, 0); OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); JUMPHERE(quit); } } else OP2(SLJIT_ADD, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); return TRUE; } #undef MAX_N_CHARS #undef MAX_DIFF_CHARS static SLJIT_INLINE void fast_forward_first_char(compiler_common *common, pcre_uchar first_char, BOOL caseless) { pcre_uchar oc; oc = first_char; if (caseless) { oc = TABLE_GET(first_char, common->fcc, first_char); #if defined SUPPORT_UCP && !defined COMPILE_PCRE8 if (first_char > 127 && common->utf) oc = UCD_OTHERCASE(first_char); #endif } fast_forward_first_char2(common, first_char, oc, 0); } static SLJIT_INLINE void fast_forward_newline(compiler_common *common) { DEFINE_COMPILER; struct sljit_label *loop; struct sljit_jump *lastchar; struct sljit_jump *firstchar; struct sljit_jump *quit; struct sljit_jump *foundcr = NULL; struct sljit_jump *notfoundnl; jump_list *newline = NULL; if (common->match_end_ptr != 0) { OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); } if (common->nltype == NLTYPE_FIXED && common->newline > 255) { lastchar = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); firstchar = CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, TMP2, 0); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(2)); OP2(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, SLJIT_UNUSED, 0, STR_PTR, 0, TMP1, 0); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER_EQUAL); #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); loop = LABEL(); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); quit = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-2)); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, loop); CMPTO(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff, loop); JUMPHERE(quit); JUMPHERE(firstchar); JUMPHERE(lastchar); if (common->match_end_ptr != 0) OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); return; } OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); firstchar = CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, TMP2, 0); skip_char_back(common); loop = LABEL(); common->ff_newline_shortcut = loop; read_char_range(common, common->nlmin, common->nlmax, TRUE); lastchar = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); if (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF) foundcr = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); check_newlinechar(common, common->nltype, &newline, FALSE); set_jumps(newline, loop); if (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF) { quit = JUMP(SLJIT_JUMP); JUMPHERE(foundcr); notfoundnl = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, CHAR_NL); OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL); #if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT); #endif OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); JUMPHERE(notfoundnl); JUMPHERE(quit); } JUMPHERE(lastchar); JUMPHERE(firstchar); if (common->match_end_ptr != 0) OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); } static BOOL check_class_ranges(compiler_common *common, const sljit_u8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks); static SLJIT_INLINE void fast_forward_start_bits(compiler_common *common, const sljit_u8 *start_bits) { DEFINE_COMPILER; struct sljit_label *start; struct sljit_jump *quit; struct sljit_jump *found = NULL; jump_list *matches = NULL; #ifndef COMPILE_PCRE8 struct sljit_jump *jump; #endif if (common->match_end_ptr != 0) { OP1(SLJIT_MOV, RETURN_ADDR, 0, STR_END, 0); OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); } start = LABEL(); quit = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); #ifdef SUPPORT_UTF if (common->utf) OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); #endif if (!check_class_ranges(common, start_bits, (start_bits[31] & 0x80) != 0, TRUE, &matches)) { #ifndef COMPILE_PCRE8 jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 255); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 255); JUMPHERE(jump); #endif OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)start_bits); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); found = JUMP(SLJIT_NOT_ZERO); } #ifdef SUPPORT_UTF if (common->utf) OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); #endif OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #ifdef SUPPORT_UTF #if defined COMPILE_PCRE8 if (common->utf) { CMPTO(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xc0, start); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); } #elif defined COMPILE_PCRE16 if (common->utf) { CMPTO(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xd800, start); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); } #endif /* COMPILE_PCRE[8|16] */ #endif /* SUPPORT_UTF */ JUMPTO(SLJIT_JUMP, start); if (found != NULL) JUMPHERE(found); if (matches != NULL) set_jumps(matches, LABEL()); JUMPHERE(quit); if (common->match_end_ptr != 0) OP1(SLJIT_MOV, STR_END, 0, RETURN_ADDR, 0); } static SLJIT_INLINE struct sljit_jump *search_requested_char(compiler_common *common, pcre_uchar req_char, BOOL caseless, BOOL has_firstchar) { DEFINE_COMPILER; struct sljit_label *loop; struct sljit_jump *toolong; struct sljit_jump *alreadyfound; struct sljit_jump *found; struct sljit_jump *foundoc = NULL; struct sljit_jump *notfound; sljit_u32 oc, bit; SLJIT_ASSERT(common->req_char_ptr != 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr); OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, REQ_BYTE_MAX); toolong = CMP(SLJIT_LESS, TMP1, 0, STR_END, 0); alreadyfound = CMP(SLJIT_LESS, STR_PTR, 0, TMP2, 0); if (has_firstchar) OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); else OP1(SLJIT_MOV, TMP1, 0, STR_PTR, 0); loop = LABEL(); notfound = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, STR_END, 0); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(TMP1), 0); oc = req_char; if (caseless) { oc = TABLE_GET(req_char, common->fcc, req_char); #if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) if (req_char > 127 && common->utf) oc = UCD_OTHERCASE(req_char); #endif } if (req_char == oc) found = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, req_char); else { bit = req_char ^ oc; if (is_powerof2(bit)) { OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, bit); found = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, req_char | bit); } else { found = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, req_char); foundoc = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, oc); } } OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPTO(SLJIT_JUMP, loop); JUMPHERE(found); if (foundoc) JUMPHERE(foundoc); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr, TMP1, 0); JUMPHERE(alreadyfound); JUMPHERE(toolong); return notfound; } static void do_revertframes(compiler_common *common) { DEFINE_COMPILER; struct sljit_jump *jump; struct sljit_label *mainloop; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP1(SLJIT_MOV, TMP3, 0, STACK_TOP, 0); GET_LOCAL_BASE(TMP1, 0, 0); /* Drop frames until we reach STACK_TOP. */ mainloop = LABEL(); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), -sizeof(sljit_sw)); jump = CMP(SLJIT_SIG_LESS_EQUAL, TMP2, 0, SLJIT_IMM, 0); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, SLJIT_MEM1(STACK_TOP), -2 * sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), sizeof(sljit_sw), SLJIT_MEM1(STACK_TOP), -3 * sizeof(sljit_sw)); OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 3 * sizeof(sljit_sw)); JUMPTO(SLJIT_JUMP, mainloop); JUMPHERE(jump); jump = CMP(SLJIT_NOT_ZERO /* SIG_LESS */, TMP2, 0, SLJIT_IMM, 0); /* End of reverting values. */ OP1(SLJIT_MOV, STACK_TOP, 0, TMP3, 0); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); JUMPHERE(jump); OP1(SLJIT_NEG, TMP2, 0, TMP2, 0); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, SLJIT_MEM1(STACK_TOP), -2 * sizeof(sljit_sw)); OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 2 * sizeof(sljit_sw)); JUMPTO(SLJIT_JUMP, mainloop); } static void check_wordboundary(compiler_common *common) { DEFINE_COMPILER; struct sljit_jump *skipread; jump_list *skipread_list = NULL; #if !(defined COMPILE_PCRE8) || defined SUPPORT_UTF struct sljit_jump *jump; #endif SLJIT_COMPILE_ASSERT(ctype_word == 0x10, ctype_word_must_be_16); sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); /* Get type of the previous char, and put it to LOCALS1. */ OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, SLJIT_IMM, 0); skipread = CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, TMP1, 0); skip_char_back(common); check_start_used_ptr(common); read_char(common); /* Testing char type. */ #ifdef SUPPORT_UCP if (common->use_ucp) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 1); jump = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_UNDERSCORE); add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Nd - ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_No - ucp_Nd); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); JUMPHERE(jump); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP2, 0); } else #endif { #ifndef COMPILE_PCRE8 jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); #elif defined SUPPORT_UTF /* Here LOCALS1 has already been zeroed. */ jump = NULL; if (common->utf) jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); #endif /* COMPILE_PCRE8 */ OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), common->ctypes); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 4 /* ctype_word */); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP1, 0); #ifndef COMPILE_PCRE8 JUMPHERE(jump); #elif defined SUPPORT_UTF if (jump != NULL) JUMPHERE(jump); #endif /* COMPILE_PCRE8 */ } JUMPHERE(skipread); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); check_str_end(common, &skipread_list); peek_char(common, READ_CHAR_MAX); /* Testing char type. This is a code duplication. */ #ifdef SUPPORT_UCP if (common->use_ucp) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 1); jump = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_UNDERSCORE); add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Nd - ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_No - ucp_Nd); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); JUMPHERE(jump); } else #endif { #ifndef COMPILE_PCRE8 /* TMP2 may be destroyed by peek_char. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); #elif defined SUPPORT_UTF OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); jump = NULL; if (common->utf) jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); #endif OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP1), common->ctypes); OP2(SLJIT_LSHR, TMP2, 0, TMP2, 0, SLJIT_IMM, 4 /* ctype_word */); OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); #ifndef COMPILE_PCRE8 JUMPHERE(jump); #elif defined SUPPORT_UTF if (jump != NULL) JUMPHERE(jump); #endif /* COMPILE_PCRE8 */ } set_jumps(skipread_list, LABEL()); OP2(SLJIT_XOR | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); sljit_emit_fast_return(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); } static BOOL check_class_ranges(compiler_common *common, const sljit_u8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks) { /* May destroy TMP1. */ DEFINE_COMPILER; int ranges[MAX_RANGE_SIZE]; sljit_u8 bit, cbit, all; int i, byte, length = 0; bit = bits[0] & 0x1; /* All bits will be zero or one (since bit is zero or one). */ all = -bit; for (i = 0; i < 256; ) { byte = i >> 3; if ((i & 0x7) == 0 && bits[byte] == all) i += 8; else { cbit = (bits[byte] >> (i & 0x7)) & 0x1; if (cbit != bit) { if (length >= MAX_RANGE_SIZE) return FALSE; ranges[length] = i; length++; bit = cbit; all = -cbit; } i++; } } if (((bit == 0) && nclass) || ((bit == 1) && !nclass)) { if (length >= MAX_RANGE_SIZE) return FALSE; ranges[length] = 256; length++; } if (length < 0 || length > 4) return FALSE; bit = bits[0] & 0x1; if (invert) bit ^= 0x1; /* No character is accepted. */ if (length == 0 && bit == 0) add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); switch(length) { case 0: /* When bit != 0, all characters are accepted. */ return TRUE; case 1: add_jump(compiler, backtracks, CMP(bit == 0 ? SLJIT_LESS : SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); return TRUE; case 2: if (ranges[0] + 1 != ranges[1]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_LESS : SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); } else add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_EQUAL : SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); return TRUE; case 3: if (bit != 0) { add_jump(compiler, backtracks, CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2])); if (ranges[0] + 1 != ranges[1]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); } else add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); return TRUE; } add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, ranges[0])); if (ranges[1] + 1 != ranges[2]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[1]); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[1])); } else add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1])); return TRUE; case 4: if ((ranges[1] - ranges[0]) == (ranges[3] - ranges[2]) && (ranges[0] | (ranges[2] - ranges[0])) == ranges[2] && (ranges[1] & (ranges[2] - ranges[0])) == 0 && is_powerof2(ranges[2] - ranges[0])) { SLJIT_ASSERT((ranges[0] & (ranges[2] - ranges[0])) == 0 && (ranges[2] & ranges[3] & (ranges[2] - ranges[0])) != 0); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[0]); if (ranges[2] + 1 != ranges[3]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2]); add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_LESS : SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[2])); } else add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_EQUAL : SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2])); return TRUE; } if (bit != 0) { i = 0; if (ranges[0] + 1 != ranges[1]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); i = ranges[0]; } else add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); if (ranges[2] + 1 != ranges[3]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - i); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[2])); } else add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2] - i)); return TRUE; } OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); add_jump(compiler, backtracks, CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[0])); if (ranges[1] + 1 != ranges[2]) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0]); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[1])); } else add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); return TRUE; default: SLJIT_UNREACHABLE(); return FALSE; } } static void check_anynewline(compiler_common *common) { /* Check whether TMP1 contains a newline character. TMP2 destroyed. */ DEFINE_COMPILER; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x0a); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x0d - 0x0a); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x0a); #if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 #ifdef COMPILE_PCRE8 if (common->utf) { #endif OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x1); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2029 - 0x0a); #ifdef COMPILE_PCRE8 } #endif #endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } static void check_hspace(compiler_common *common) { /* Check whether TMP1 contains a newline character. TMP2 destroyed. */ DEFINE_COMPILER; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x09); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x20); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xa0); #if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 #ifdef COMPILE_PCRE8 if (common->utf) { #endif OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x1680); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x2000); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x200A - 0x2000); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x202f - 0x2000); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x205f - 0x2000); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x3000 - 0x2000); #ifdef COMPILE_PCRE8 } #endif #endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } static void check_vspace(compiler_common *common) { /* Check whether TMP1 contains a newline character. TMP2 destroyed. */ DEFINE_COMPILER; sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x0a); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x0d - 0x0a); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x0a); #if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 #ifdef COMPILE_PCRE8 if (common->utf) { #endif OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x1); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2029 - 0x0a); #ifdef COMPILE_PCRE8 } #endif #endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); sljit_emit_fast_return(compiler, RETURN_ADDR, 0); } static void do_casefulcmp(compiler_common *common) { DEFINE_COMPILER; struct sljit_jump *jump; struct sljit_label *label; int char1_reg; int char2_reg; if (sljit_get_register_index(TMP3) < 0) { char1_reg = STR_END; char2_reg = STACK_TOP; } else { char1_reg = TMP3; char2_reg = RETURN_ADDR; } sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); if (char1_reg == STR_END) { OP1(SLJIT_MOV, TMP3, 0, char1_reg, 0); OP1(SLJIT_MOV, RETURN_ADDR, 0, char2_reg, 0); } if (sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_SUPP | SLJIT_MEM_POST, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)) == SLJIT_SUCCESS) { label = LABEL(); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_POST, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_POST, char2_reg, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); jump = CMP(SLJIT_NOT_EQUAL, char1_reg, 0, char2_reg, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPTO(SLJIT_NOT_ZERO, label); JUMPHERE(jump); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); } else if (sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_SUPP | SLJIT_MEM_PRE, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)) == SLJIT_SUCCESS) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); label = LABEL(); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_PRE, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_PRE, char2_reg, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); jump = CMP(SLJIT_NOT_EQUAL, char1_reg, 0, char2_reg, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPTO(SLJIT_NOT_ZERO, label); JUMPHERE(jump); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } else { label = LABEL(); OP1(MOV_UCHAR, char1_reg, 0, SLJIT_MEM1(TMP1), 0); OP1(MOV_UCHAR, char2_reg, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); jump = CMP(SLJIT_NOT_EQUAL, char1_reg, 0, char2_reg, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPTO(SLJIT_NOT_ZERO, label); JUMPHERE(jump); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); } if (char1_reg == STR_END) { OP1(SLJIT_MOV, char1_reg, 0, TMP3, 0); OP1(SLJIT_MOV, char2_reg, 0, RETURN_ADDR, 0); } sljit_emit_fast_return(compiler, TMP1, 0); } static void do_caselesscmp(compiler_common *common) { DEFINE_COMPILER; struct sljit_jump *jump; struct sljit_label *label; int char1_reg = STR_END; int char2_reg; int lcc_table; int opt_type = 0; if (sljit_get_register_index(TMP3) < 0) { char2_reg = STACK_TOP; lcc_table = STACK_LIMIT; } else { char2_reg = RETURN_ADDR; lcc_table = TMP3; } if (sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_SUPP | SLJIT_MEM_POST, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)) == SLJIT_SUCCESS) opt_type = 1; else if (sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_SUPP | SLJIT_MEM_PRE, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)) == SLJIT_SUCCESS) opt_type = 2; sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, char1_reg, 0); if (char2_reg == STACK_TOP) { OP1(SLJIT_MOV, TMP3, 0, char2_reg, 0); OP1(SLJIT_MOV, RETURN_ADDR, 0, lcc_table, 0); } OP1(SLJIT_MOV, lcc_table, 0, SLJIT_IMM, common->lcc); if (opt_type == 1) { label = LABEL(); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_POST, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_POST, char2_reg, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); } else if (opt_type == 2) { OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); label = LABEL(); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_PRE, char1_reg, SLJIT_MEM1(TMP1), IN_UCHARS(1)); sljit_emit_mem(compiler, MOV_UCHAR | SLJIT_MEM_PRE, char2_reg, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); } else { label = LABEL(); OP1(MOV_UCHAR, char1_reg, 0, SLJIT_MEM1(TMP1), 0); OP1(MOV_UCHAR, char2_reg, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); } #ifndef COMPILE_PCRE8 jump = CMP(SLJIT_GREATER, char1_reg, 0, SLJIT_IMM, 255); #endif OP1(SLJIT_MOV_U8, char1_reg, 0, SLJIT_MEM2(lcc_table, char1_reg), 0); #ifndef COMPILE_PCRE8 JUMPHERE(jump); jump = CMP(SLJIT_GREATER, char2_reg, 0, SLJIT_IMM, 255); #endif OP1(SLJIT_MOV_U8, char2_reg, 0, SLJIT_MEM2(lcc_table, char2_reg), 0); #ifndef COMPILE_PCRE8 JUMPHERE(jump); #endif if (opt_type == 0) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); jump = CMP(SLJIT_NOT_EQUAL, char1_reg, 0, char2_reg, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); JUMPTO(SLJIT_NOT_ZERO, label); JUMPHERE(jump); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); if (opt_type == 2) OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); if (char2_reg == STACK_TOP) { OP1(SLJIT_MOV, char2_reg, 0, TMP3, 0); OP1(SLJIT_MOV, lcc_table, 0, RETURN_ADDR, 0); } OP1(SLJIT_MOV, char1_reg, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); sljit_emit_fast_return(compiler, TMP1, 0); } #if defined SUPPORT_UTF && defined SUPPORT_UCP static const pcre_uchar * SLJIT_FUNC do_utf_caselesscmp(pcre_uchar *src1, pcre_uchar *src2, pcre_uchar *end1, pcre_uchar *end2) { /* This function would be ineffective to do in JIT level. */ sljit_u32 c1, c2; const ucd_record *ur; const sljit_u32 *pp; while (src1 < end1) { if (src2 >= end2) return (pcre_uchar*)1; GETCHARINC(c1, src1); GETCHARINC(c2, src2); ur = GET_UCD(c2); if (c1 != c2 && c1 != c2 + ur->other_case) { pp = PRIV(ucd_caseless_sets) + ur->caseset; for (;;) { if (c1 < *pp) return NULL; if (c1 == *pp++) break; } } } return src2; } #endif /* SUPPORT_UTF && SUPPORT_UCP */ static pcre_uchar *byte_sequence_compare(compiler_common *common, BOOL caseless, pcre_uchar *cc, compare_context *context, jump_list **backtracks) { DEFINE_COMPILER; unsigned int othercasebit = 0; pcre_uchar *othercasechar = NULL; #ifdef SUPPORT_UTF int utflength; #endif if (caseless && char_has_othercase(common, cc)) { othercasebit = char_get_othercase_bit(common, cc); SLJIT_ASSERT(othercasebit); /* Extracting bit difference info. */ #if defined COMPILE_PCRE8 othercasechar = cc + (othercasebit >> 8); othercasebit &= 0xff; #elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 /* Note that this code only handles characters in the BMP. If there ever are characters outside the BMP whose othercase differs in only one bit from itself (there currently are none), this code will need to be revised for COMPILE_PCRE32. */ othercasechar = cc + (othercasebit >> 9); if ((othercasebit & 0x100) != 0) othercasebit = (othercasebit & 0xff) << 8; else othercasebit &= 0xff; #endif /* COMPILE_PCRE[8|16|32] */ } if (context->sourcereg == -1) { #if defined COMPILE_PCRE8 #if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED if (context->length >= 4) OP1(SLJIT_MOV_S32, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); else if (context->length >= 2) OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); else #endif OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); #elif defined COMPILE_PCRE16 #if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED if (context->length >= 4) OP1(SLJIT_MOV_S32, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); else #endif OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); #elif defined COMPILE_PCRE32 OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); #endif /* COMPILE_PCRE[8|16|32] */ context->sourcereg = TMP2; } #ifdef SUPPORT_UTF utflength = 1; if (common->utf && HAS_EXTRALEN(*cc)) utflength += GET_EXTRALEN(*cc); do { #endif context->length -= IN_UCHARS(1); #if (defined SLJIT_UNALIGNED && SLJIT_UNALIGNED) && (defined COMPILE_PCRE8 || defined COMPILE_PCRE16) /* Unaligned read is supported. */ if (othercasebit != 0 && othercasechar == cc) { context->c.asuchars[context->ucharptr] = *cc | othercasebit; context->oc.asuchars[context->ucharptr] = othercasebit; } else { context->c.asuchars[context->ucharptr] = *cc; context->oc.asuchars[context->ucharptr] = 0; } context->ucharptr++; #if defined COMPILE_PCRE8 if (context->ucharptr >= 4 || context->length == 0 || (context->ucharptr == 2 && context->length == 1)) #else if (context->ucharptr >= 2 || context->length == 0) #endif { if (context->length >= 4) OP1(SLJIT_MOV_S32, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); else if (context->length >= 2) OP1(SLJIT_MOV_U16, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); #if defined COMPILE_PCRE8 else if (context->length >= 1) OP1(SLJIT_MOV_U8, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); #endif /* COMPILE_PCRE8 */ context->sourcereg = context->sourcereg == TMP1 ? TMP2 : TMP1; switch(context->ucharptr) { case 4 / sizeof(pcre_uchar): if (context->oc.asint != 0) OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asint); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asint | context->oc.asint)); break; case 2 / sizeof(pcre_uchar): if (context->oc.asushort != 0) OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asushort); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asushort | context->oc.asushort)); break; #ifdef COMPILE_PCRE8 case 1: if (context->oc.asbyte != 0) OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asbyte); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asbyte | context->oc.asbyte)); break; #endif default: SLJIT_UNREACHABLE(); break; } context->ucharptr = 0; } #else /* Unaligned read is unsupported or in 32 bit mode. */ if (context->length >= 1) OP1(MOV_UCHAR, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); context->sourcereg = context->sourcereg == TMP1 ? TMP2 : TMP1; if (othercasebit != 0 && othercasechar == cc) { OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, othercasebit); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, *cc | othercasebit)); } else add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, *cc)); #endif cc++; #ifdef SUPPORT_UTF utflength--; } while (utflength > 0); #endif return cc; } #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 #define SET_TYPE_OFFSET(value) \ if ((value) != typeoffset) \ { \ if ((value) < typeoffset) \ OP2(SLJIT_ADD, typereg, 0, typereg, 0, SLJIT_IMM, typeoffset - (value)); \ else \ OP2(SLJIT_SUB, typereg, 0, typereg, 0, SLJIT_IMM, (value) - typeoffset); \ } \ typeoffset = (value); #define SET_CHAR_OFFSET(value) \ if ((value) != charoffset) \ { \ if ((value) < charoffset) \ OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(charoffset - (value))); \ else \ OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)((value) - charoffset)); \ } \ charoffset = (value); static pcre_uchar *compile_char1_matchingpath(compiler_common *common, pcre_uchar type, pcre_uchar *cc, jump_list **backtracks, BOOL check_str_ptr); static void compile_xclass_matchingpath(compiler_common *common, pcre_uchar *cc, jump_list **backtracks) { DEFINE_COMPILER; jump_list *found = NULL; jump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks; sljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX; struct sljit_jump *jump = NULL; pcre_uchar *ccbegin; int compares, invertcmp, numberofcmps; #if defined SUPPORT_UTF && (defined COMPILE_PCRE8 || defined COMPILE_PCRE16) BOOL utf = common->utf; #endif #ifdef SUPPORT_UCP BOOL needstype = FALSE, needsscript = FALSE, needschar = FALSE; BOOL charsaved = FALSE; int typereg = TMP1; const sljit_u32 *other_cases; sljit_uw typeoffset; #endif /* Scanning the necessary info. */ cc++; ccbegin = cc; compares = 0; if (cc[-1] & XCL_MAP) { min = 0; cc += 32 / sizeof(pcre_uchar); } while (*cc != XCL_END) { compares++; if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); if (c > max) max = c; if (c < min) min = c; #ifdef SUPPORT_UCP needschar = TRUE; #endif } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); if (c < min) min = c; GETCHARINCTEST(c, cc); if (c > max) max = c; #ifdef SUPPORT_UCP needschar = TRUE; #endif } #ifdef SUPPORT_UCP else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; if (*cc == PT_CLIST) { other_cases = PRIV(ucd_caseless_sets) + cc[1]; while (*other_cases != NOTACHAR) { if (*other_cases > max) max = *other_cases; if (*other_cases < min) min = *other_cases; other_cases++; } } else { max = READ_CHAR_MAX; min = 0; } switch(*cc) { case PT_ANY: /* Any either accepts everything or ignored. */ if (cc[-1] == XCL_PROP) { compile_char1_matchingpath(common, OP_ALLANY, cc, backtracks, FALSE); if (list == backtracks) add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); return; } break; case PT_LAMP: case PT_GC: case PT_PC: case PT_ALNUM: needstype = TRUE; break; case PT_SC: needsscript = TRUE; break; case PT_SPACE: case PT_PXSPACE: case PT_WORD: case PT_PXGRAPH: case PT_PXPRINT: case PT_PXPUNCT: needstype = TRUE; needschar = TRUE; break; case PT_CLIST: case PT_UCNC: needschar = TRUE; break; default: SLJIT_UNREACHABLE(); break; } cc += 2; } #endif } SLJIT_ASSERT(compares > 0); /* We are not necessary in utf mode even in 8 bit mode. */ cc = ccbegin; read_char_range(common, min, max, (cc[-1] & XCL_NOT) != 0); if ((cc[-1] & XCL_HASPROP) == 0) { if ((cc[-1] & XCL_MAP) != 0) { jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); if (!check_class_ranges(common, (const sljit_u8 *)cc, (((const sljit_u8 *)cc)[31] & 0x80) != 0, TRUE, &found)) { OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); add_jump(compiler, &found, JUMP(SLJIT_NOT_ZERO)); } add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(jump); cc += 32 / sizeof(pcre_uchar); } else { OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min); add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, max - min)); } } else if ((cc[-1] & XCL_MAP) != 0) { OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); #ifdef SUPPORT_UCP charsaved = TRUE; #endif if (!check_class_ranges(common, (const sljit_u8 *)cc, FALSE, TRUE, list)) { #ifdef COMPILE_PCRE8 jump = NULL; if (common->utf) #endif jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO)); #ifdef COMPILE_PCRE8 if (common->utf) #endif JUMPHERE(jump); } OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0); cc += 32 / sizeof(pcre_uchar); } #ifdef SUPPORT_UCP if (needstype || needsscript) { if (needschar && !charsaved) OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); #ifdef COMPILE_PCRE32 if (!common->utf) { jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0x10ffff + 1); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, INVALID_UTF_CHAR); JUMPHERE(jump); } #endif OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1)); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK); OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2)); OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1); /* Before anything else, we deal with scripts. */ if (needsscript) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM2(TMP1, TMP2), 3); ccbegin = cc; while (*cc != XCL_END) { if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); GETCHARINCTEST(c, cc); } else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); cc++; if (*cc == PT_SC) { compares--; invertcmp = (compares == 0 && list != backtracks); if (cc[-1] == XCL_NOTPROP) invertcmp ^= 0x1; jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]); add_jump(compiler, compares > 0 ? list : backtracks, jump); } cc += 2; } } cc = ccbegin; } if (needschar) { OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0); } if (needstype) { if (!needschar) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype)); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM2(TMP1, TMP2), 3); } else { OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, RETURN_ADDR, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype)); typereg = RETURN_ADDR; } } } #endif /* Generating code. */ charoffset = 0; numberofcmps = 0; #ifdef SUPPORT_UCP typeoffset = 0; #endif while (*cc != XCL_END) { compares--; invertcmp = (compares == 0 && list != backtracks); jump = NULL; if (*cc == XCL_SINGLE) { cc ++; GETCHARINCTEST(c, cc); if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) { OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_EQUAL); numberofcmps++; } else if (numberofcmps > 0) { OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); numberofcmps = 0; } else { jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); numberofcmps = 0; } } else if (*cc == XCL_RANGE) { cc ++; GETCHARINCTEST(c, cc); SET_CHAR_OFFSET(c); GETCHARINCTEST(c, cc); if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) { OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); numberofcmps++; } else if (numberofcmps > 0) { OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); numberofcmps = 0; } else { jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); numberofcmps = 0; } } #ifdef SUPPORT_UCP else { SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); if (*cc == XCL_NOTPROP) invertcmp ^= 0x1; cc++; switch(*cc) { case PT_ANY: if (!invertcmp) jump = JUMP(SLJIT_JUMP); break; case PT_LAMP: OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_GC: c = PRIV(ucp_typerange)[(int)cc[1] * 2]; SET_TYPE_OFFSET(c); jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c); break; case PT_PC: jump = CMP(SLJIT_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset); break; case PT_SC: compares++; /* Do nothing. */ break; case PT_SPACE: case PT_PXSPACE: SET_CHAR_OFFSET(9); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd - 0x9); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x9); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e - 0x9); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); SET_TYPE_OFFSET(ucp_Zl); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_WORD: OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset)); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); /* Fall through. */ case PT_ALNUM: SET_TYPE_OFFSET(ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); SET_TYPE_OFFSET(ucp_Nd); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_CLIST: other_cases = PRIV(ucd_caseless_sets) + cc[1]; /* At least three characters are required. Otherwise this case would be handled by the normal code path. */ SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR); SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]); /* Optimizing character pairs, if their difference is power of 2. */ if (is_powerof2(other_cases[1] ^ other_cases[0])) { if (charoffset == 0) OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); else { OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); } OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, other_cases[1]); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); other_cases += 2; } else if (is_powerof2(other_cases[2] ^ other_cases[1])) { if (charoffset == 0) OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]); else { OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); } OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, other_cases[2]); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset)); OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL); other_cases += 3; } else { OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); } while (*other_cases != NOTACHAR) { OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL); } jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_UCNC: OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset)); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset)); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset)); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); SET_CHAR_OFFSET(0xa0); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset)); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL); SET_CHAR_OFFSET(0); OP2(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xe000 - 0); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_GREATER_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; case PT_PXGRAPH: /* C and Z groups are the farthest two groups. */ SET_TYPE_OFFSET(ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_GREATER, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER); jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); /* In case of ucp_Cf, we overwrite the result. */ SET_CHAR_OFFSET(0x2066); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); JUMPHERE(jump); jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); break; case PT_PXPRINT: /* C and Z groups are the farthest two groups. */ SET_TYPE_OFFSET(ucp_Ll); OP2(SLJIT_SUB | SLJIT_SET_GREATER, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll); OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_NOT_EQUAL); jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); /* In case of ucp_Cf, we overwrite the result. */ SET_CHAR_OFFSET(0x2066); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL); JUMPHERE(jump); jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); break; case PT_PXPUNCT: SET_TYPE_OFFSET(ucp_Sc); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL); SET_CHAR_OFFSET(0); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x7f); OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_LESS_EQUAL); SET_TYPE_OFFSET(ucp_Pc); OP2(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL); jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp); break; default: SLJIT_UNREACHABLE(); break; } cc += 2; } #endif if (jump != NULL) add_jump(compiler, compares > 0 ? list : backtracks, jump); } if (found != NULL) set_jumps(found, LABEL()); } #undef SET_TYPE_OFFSET #undef SET_CHAR_OFFSET #endif static pcre_uchar *compile_simple_assertion_matchingpath(compiler_common *common, pcre_uchar type, pcre_uchar *cc, jump_list **backtracks) { DEFINE_COMPILER; int length; struct sljit_jump *jump[4]; #ifdef SUPPORT_UTF struct sljit_label *label; #endif /* SUPPORT_UTF */ switch(type) { case OP_SOD: OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, TMP1, 0)); return cc; case OP_SOM: OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, TMP1, 0)); return cc; case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: add_jump(compiler, &common->wordboundary, JUMP(SLJIT_FAST_CALL)); sljit_set_current_flags(compiler, SLJIT_SET_Z); add_jump(compiler, backtracks, JUMP(type == OP_NOT_WORD_BOUNDARY ? SLJIT_NOT_ZERO : SLJIT_ZERO)); return cc; case OP_EODN: /* Requires rather complex checks. */ jump[0] = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); if (common->nltype == NLTYPE_FIXED && common->newline > 255) { OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); if (common->mode == JIT_COMPILE) add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, STR_END, 0)); else { jump[1] = CMP(SLJIT_EQUAL, TMP2, 0, STR_END, 0); OP2(SLJIT_SUB | SLJIT_SET_LESS, SLJIT_UNUSED, 0, TMP2, 0, STR_END, 0); OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff); OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_NOT_EQUAL); add_jump(compiler, backtracks, JUMP(SLJIT_NOT_EQUAL)); check_partial(common, TRUE); add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(jump[1]); } OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); } else if (common->nltype == NLTYPE_FIXED) { OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, STR_END, 0)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline)); } else { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); jump[1] = CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); OP2(SLJIT_SUB | SLJIT_SET_Z | SLJIT_SET_GREATER, SLJIT_UNUSED, 0, TMP2, 0, STR_END, 0); jump[2] = JUMP(SLJIT_GREATER); add_jump(compiler, backtracks, JUMP(SLJIT_NOT_EQUAL) /* LESS */); /* Equal. */ OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); jump[3] = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL); add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(jump[1]); if (common->nltype == NLTYPE_ANYCRLF) { OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP2, 0, STR_END, 0)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); } else { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, STR_PTR, 0); read_char_range(common, common->nlmin, common->nlmax, TRUE); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, STR_END, 0)); add_jump(compiler, &common->anynewline, JUMP(SLJIT_FAST_CALL)); sljit_set_current_flags(compiler, SLJIT_SET_Z); add_jump(compiler, backtracks, JUMP(SLJIT_ZERO)); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); } JUMPHERE(jump[2]); JUMPHERE(jump[3]); } JUMPHERE(jump[0]); check_partial(common, FALSE); return cc; case OP_EOD: add_jump(compiler, backtracks, CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0)); check_partial(common, FALSE); return cc; case OP_DOLL: OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, noteol)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); if (!common->endonly) compile_simple_assertion_matchingpath(common, OP_EODN, cc, backtracks); else { add_jump(compiler, backtracks, CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0)); check_partial(common, FALSE); } return cc; case OP_DOLLM: jump[1] = CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0); OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, noteol)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); check_partial(common, FALSE); jump[0] = JUMP(SLJIT_JUMP); JUMPHERE(jump[1]); if (common->nltype == NLTYPE_FIXED && common->newline > 255) { OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); if (common->mode == JIT_COMPILE) add_jump(compiler, backtracks, CMP(SLJIT_GREATER, TMP2, 0, STR_END, 0)); else { jump[1] = CMP(SLJIT_LESS_EQUAL, TMP2, 0, STR_END, 0); /* STR_PTR = STR_END - IN_UCHARS(1) */ add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); check_partial(common, TRUE); add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(jump[1]); } OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); } else { peek_char(common, common->nlmax); check_newlinechar(common, common->nltype, backtracks, FALSE); } JUMPHERE(jump[0]); return cc; case OP_CIRC: OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, begin)); add_jump(compiler, backtracks, CMP(SLJIT_GREATER, STR_PTR, 0, TMP1, 0)); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, notbol)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); return cc; case OP_CIRCM: OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, begin)); jump[1] = CMP(SLJIT_GREATER, STR_PTR, 0, TMP1, 0); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, notbol)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); jump[0] = JUMP(SLJIT_JUMP); JUMPHERE(jump[1]); add_jump(compiler, backtracks, CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); if (common->nltype == NLTYPE_FIXED && common->newline > 255) { OP2(SLJIT_SUB, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); add_jump(compiler, backtracks, CMP(SLJIT_LESS, TMP2, 0, TMP1, 0)); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-2)); OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); } else { skip_char_back(common); read_char_range(common, common->nlmin, common->nlmax, TRUE); check_newlinechar(common, common->nltype, backtracks, FALSE); } JUMPHERE(jump[0]); return cc; case OP_REVERSE: length = GET(cc, 0); if (length == 0) return cc + LINK_SIZE; OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); #ifdef SUPPORT_UTF if (common->utf) { OP1(SLJIT_MOV, TMP3, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, length); label = LABEL(); add_jump(compiler, backtracks, CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, TMP3, 0)); skip_char_back(common); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); } else #endif { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(length)); add_jump(compiler, backtracks, CMP(SLJIT_LESS, STR_PTR, 0, TMP1, 0)); } check_start_used_ptr(common); return cc + LINK_SIZE; } SLJIT_UNREACHABLE(); return cc; } static pcre_uchar *compile_char1_matchingpath(compiler_common *common, pcre_uchar type, pcre_uchar *cc, jump_list **backtracks, BOOL check_str_ptr) { DEFINE_COMPILER; int length; unsigned int c, oc, bit; compare_context context; struct sljit_jump *jump[3]; jump_list *end_list; #ifdef SUPPORT_UTF struct sljit_label *label; #ifdef SUPPORT_UCP pcre_uchar propdata[5]; #endif #endif /* SUPPORT_UTF */ switch(type) { case OP_NOT_DIGIT: case OP_DIGIT: /* Digits are usually 0-9, so it is worth to optimize them. */ if (check_str_ptr) detect_partial_match(common, backtracks); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && is_char7_bitset((const sljit_u8 *)common->ctypes - cbit_length + cbit_digit, FALSE)) read_char7_type(common, type == OP_NOT_DIGIT); else #endif read_char8_type(common, type == OP_NOT_DIGIT); /* Flip the starting bit in the negative case. */ OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_digit); add_jump(compiler, backtracks, JUMP(type == OP_DIGIT ? SLJIT_ZERO : SLJIT_NOT_ZERO)); return cc; case OP_NOT_WHITESPACE: case OP_WHITESPACE: if (check_str_ptr) detect_partial_match(common, backtracks); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && is_char7_bitset((const sljit_u8 *)common->ctypes - cbit_length + cbit_space, FALSE)) read_char7_type(common, type == OP_NOT_WHITESPACE); else #endif read_char8_type(common, type == OP_NOT_WHITESPACE); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_space); add_jump(compiler, backtracks, JUMP(type == OP_WHITESPACE ? SLJIT_ZERO : SLJIT_NOT_ZERO)); return cc; case OP_NOT_WORDCHAR: case OP_WORDCHAR: if (check_str_ptr) detect_partial_match(common, backtracks); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 if (common->utf && is_char7_bitset((const sljit_u8 *)common->ctypes - cbit_length + cbit_word, FALSE)) read_char7_type(common, type == OP_NOT_WORDCHAR); else #endif read_char8_type(common, type == OP_NOT_WORDCHAR); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_word); add_jump(compiler, backtracks, JUMP(type == OP_WORDCHAR ? SLJIT_ZERO : SLJIT_NOT_ZERO)); return cc; case OP_ANY: if (check_str_ptr) detect_partial_match(common, backtracks); read_char_range(common, common->nlmin, common->nlmax, TRUE); if (common->nltype == NLTYPE_FIXED && common->newline > 255) { jump[0] = CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff); end_list = NULL; if (common->mode != JIT_PARTIAL_HARD_COMPILE) add_jump(compiler, &end_list, CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); else check_str_end(common, &end_list); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline & 0xff)); set_jumps(end_list, LABEL()); JUMPHERE(jump[0]); } else check_newlinechar(common, common->nltype, backtracks, TRUE); return cc; case OP_ALLANY: if (check_str_ptr) detect_partial_match(common, backtracks); #ifdef SUPPORT_UTF if (common->utf) { OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); #if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 #if defined COMPILE_PCRE8 jump[0] = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xc0); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); #elif defined COMPILE_PCRE16 jump[0] = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xd800); OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL); OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); #endif JUMPHERE(jump[0]); #endif /* COMPILE_PCRE[8|16] */ return cc; } #endif OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); return cc; case OP_ANYBYTE: if (check_str_ptr) detect_partial_match(common, backtracks); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); return cc; #ifdef SUPPORT_UTF #ifdef SUPPORT_UCP case OP_NOTPROP: case OP_PROP: propdata[0] = XCL_HASPROP; propdata[1] = type == OP_NOTPROP ? XCL_NOTPROP : XCL_PROP; propdata[2] = cc[0]; propdata[3] = cc[1]; propdata[4] = XCL_END; if (check_str_ptr) detect_partial_match(common, backtracks); compile_xclass_matchingpath(common, propdata, backtracks); return cc + 2; #endif #endif case OP_ANYNL: if (check_str_ptr) detect_partial_match(common, backtracks); read_char_range(common, common->bsr_nlmin, common->bsr_nlmax, FALSE); jump[0] = CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); /* We don't need to handle soft partial matching case. */ end_list = NULL; if (common->mode != JIT_PARTIAL_HARD_COMPILE) add_jump(compiler, &end_list, CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); else check_str_end(common, &end_list); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); jump[1] = CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); jump[2] = JUMP(SLJIT_JUMP); JUMPHERE(jump[0]); check_newlinechar(common, common->bsr_nltype, backtracks, FALSE); set_jumps(end_list, LABEL()); JUMPHERE(jump[1]); JUMPHERE(jump[2]); return cc; case OP_NOT_HSPACE: case OP_HSPACE: if (check_str_ptr) detect_partial_match(common, backtracks); read_char_range(common, 0x9, 0x3000, type == OP_NOT_HSPACE); add_jump(compiler, &common->hspace, JUMP(SLJIT_FAST_CALL)); sljit_set_current_flags(compiler, SLJIT_SET_Z); add_jump(compiler, backtracks, JUMP(type == OP_NOT_HSPACE ? SLJIT_NOT_ZERO : SLJIT_ZERO)); return cc; case OP_NOT_VSPACE: case OP_VSPACE: if (check_str_ptr) detect_partial_match(common, backtracks); read_char_range(common, 0xa, 0x2029, type == OP_NOT_VSPACE); add_jump(compiler, &common->vspace, JUMP(SLJIT_FAST_CALL)); sljit_set_current_flags(compiler, SLJIT_SET_Z); add_jump(compiler, backtracks, JUMP(type == OP_NOT_VSPACE ? SLJIT_NOT_ZERO : SLJIT_ZERO)); return cc; #ifdef SUPPORT_UCP case OP_EXTUNI: if (check_str_ptr) detect_partial_match(common, backtracks); read_char(common); add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, gbprop)); /* Optimize register allocation: use a real register. */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); OP1(SLJIT_MOV_U8, STACK_TOP, 0, SLJIT_MEM2(TMP1, TMP2), 3); label = LABEL(); jump[0] = CMP(SLJIT_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); read_char(common); add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, gbprop)); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM2(TMP1, TMP2), 3); OP2(SLJIT_SHL, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 2); OP1(SLJIT_MOV_U32, TMP1, 0, SLJIT_MEM1(STACK_TOP), (sljit_sw)PRIV(ucp_gbtable)); OP1(SLJIT_MOV, STACK_TOP, 0, TMP2, 0); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); JUMPTO(SLJIT_NOT_ZERO, label); OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); JUMPHERE(jump[0]); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); if (common->mode == JIT_PARTIAL_HARD_COMPILE) { jump[0] = CMP(SLJIT_LESS, STR_PTR, 0, STR_END, 0); /* Since we successfully read a char above, partial matching must occure. */ check_partial(common, TRUE); JUMPHERE(jump[0]); } return cc; #endif case OP_CHAR: case OP_CHARI: length = 1; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(*cc)) length += GET_EXTRALEN(*cc); #endif if (common->mode == JIT_COMPILE && check_str_ptr && (type == OP_CHAR || !char_has_othercase(common, cc) || char_get_othercase_bit(common, cc) != 0)) { OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(length)); add_jump(compiler, backtracks, CMP(SLJIT_GREATER, STR_PTR, 0, STR_END, 0)); context.length = IN_UCHARS(length); context.sourcereg = -1; #if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED context.ucharptr = 0; #endif return byte_sequence_compare(common, type == OP_CHARI, cc, &context, backtracks); } if (check_str_ptr) detect_partial_match(common, backtracks); #ifdef SUPPORT_UTF if (common->utf) { GETCHAR(c, cc); } else #endif c = *cc; if (type == OP_CHAR || !char_has_othercase(common, cc)) { read_char_range(common, c, c, FALSE); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, c)); return cc + length; } oc = char_othercase(common, c); read_char_range(common, c < oc ? c : oc, c > oc ? c : oc, FALSE); bit = c ^ oc; if (is_powerof2(bit)) { OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, bit); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, c | bit)); return cc + length; } jump[0] = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, c); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, oc)); JUMPHERE(jump[0]); return cc + length; case OP_NOT: case OP_NOTI: if (check_str_ptr) detect_partial_match(common, backtracks); length = 1; #ifdef SUPPORT_UTF if (common->utf) { #ifdef COMPILE_PCRE8 c = *cc; if (c < 128) { OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); if (type == OP_NOT || !char_has_othercase(common, cc)) add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, c)); else { /* Since UTF8 code page is fixed, we know that c is in [a-z] or [A-Z] range. */ OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x20); add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, c | 0x20)); } /* Skip the variable-length character. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); jump[0] = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0xc0); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); JUMPHERE(jump[0]); return cc + 1; } else #endif /* COMPILE_PCRE8 */ { GETCHARLEN(c, cc, length); } } else #endif /* SUPPORT_UTF */ c = *cc; if (type == OP_NOT || !char_has_othercase(common, cc)) { read_char_range(common, c, c, TRUE); add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, c)); } else { oc = char_othercase(common, c); read_char_range(common, c < oc ? c : oc, c > oc ? c : oc, TRUE); bit = c ^ oc; if (is_powerof2(bit)) { OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, bit); add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, c | bit)); } else { add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, c)); add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, oc)); } } return cc + length; case OP_CLASS: case OP_NCLASS: if (check_str_ptr) detect_partial_match(common, backtracks); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 bit = (common->utf && is_char7_bitset((const sljit_u8 *)cc, type == OP_NCLASS)) ? 127 : 255; read_char_range(common, 0, bit, type == OP_NCLASS); #else read_char_range(common, 0, 255, type == OP_NCLASS); #endif if (check_class_ranges(common, (const sljit_u8 *)cc, type == OP_NCLASS, FALSE, backtracks)) return cc + 32 / sizeof(pcre_uchar); #if defined SUPPORT_UTF && defined COMPILE_PCRE8 jump[0] = NULL; if (common->utf) { jump[0] = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, bit); if (type == OP_CLASS) { add_jump(compiler, backtracks, jump[0]); jump[0] = NULL; } } #elif !defined COMPILE_PCRE8 jump[0] = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255); if (type == OP_CLASS) { add_jump(compiler, backtracks, jump[0]); jump[0] = NULL; } #endif /* SUPPORT_UTF && COMPILE_PCRE8 */ OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); OP2(SLJIT_AND | SLJIT_SET_Z, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); add_jump(compiler, backtracks, JUMP(SLJIT_ZERO)); #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 if (jump[0] != NULL) JUMPHERE(jump[0]); #endif return cc + 32 / sizeof(pcre_uchar); #if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 case OP_XCLASS: if (check_str_ptr) detect_partial_match(common, backtracks); compile_xclass_matchingpath(common, cc + LINK_SIZE, backtracks); return cc + GET(cc, 0) - 1; #endif } SLJIT_UNREACHABLE(); return cc; } static SLJIT_INLINE pcre_uchar *compile_charn_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, jump_list **backtracks) { /* This function consumes at least one input character. */ /* To decrease the number of length checks, we try to concatenate the fixed length character sequences. */ DEFINE_COMPILER; pcre_uchar *ccbegin = cc; compare_context context; int size; context.length = 0; do { if (cc >= ccend) break; if (*cc == OP_CHAR) { size = 1; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(cc[1])) size += GET_EXTRALEN(cc[1]); #endif } else if (*cc == OP_CHARI) { size = 1; #ifdef SUPPORT_UTF if (common->utf) { if (char_has_othercase(common, cc + 1) && char_get_othercase_bit(common, cc + 1) == 0) size = 0; else if (HAS_EXTRALEN(cc[1])) size += GET_EXTRALEN(cc[1]); } else #endif if (char_has_othercase(common, cc + 1) && char_get_othercase_bit(common, cc + 1) == 0) size = 0; } else size = 0; cc += 1 + size; context.length += IN_UCHARS(size); } while (size > 0 && context.length <= 128); cc = ccbegin; if (context.length > 0) { /* We have a fixed-length byte sequence. */ OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, context.length); add_jump(compiler, backtracks, CMP(SLJIT_GREATER, STR_PTR, 0, STR_END, 0)); context.sourcereg = -1; #if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED context.ucharptr = 0; #endif do cc = byte_sequence_compare(common, *cc == OP_CHARI, cc + 1, &context, backtracks); while (context.length > 0); return cc; } /* A non-fixed length character will be checked if length == 0. */ return compile_char1_matchingpath(common, *cc, cc + 1, backtracks, TRUE); } /* Forward definitions. */ static void compile_matchingpath(compiler_common *, pcre_uchar *, pcre_uchar *, backtrack_common *); static void compile_backtrackingpath(compiler_common *, struct backtrack_common *); #define PUSH_BACKTRACK(size, ccstart, error) \ do \ { \ backtrack = sljit_alloc_memory(compiler, (size)); \ if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ return error; \ memset(backtrack, 0, size); \ backtrack->prev = parent->top; \ backtrack->cc = (ccstart); \ parent->top = backtrack; \ } \ while (0) #define PUSH_BACKTRACK_NOVALUE(size, ccstart) \ do \ { \ backtrack = sljit_alloc_memory(compiler, (size)); \ if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ return; \ memset(backtrack, 0, size); \ backtrack->prev = parent->top; \ backtrack->cc = (ccstart); \ parent->top = backtrack; \ } \ while (0) #define BACKTRACK_AS(type) ((type *)backtrack) static void compile_dnref_search(compiler_common *common, pcre_uchar *cc, jump_list **backtracks) { /* The OVECTOR offset goes to TMP2. */ DEFINE_COMPILER; int count = GET2(cc, 1 + IMM2_SIZE); pcre_uchar *slot = common->name_table + GET2(cc, 1) * common->name_entry_size; unsigned int offset; jump_list *found = NULL; SLJIT_ASSERT(*cc == OP_DNREF || *cc == OP_DNREFI); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); count--; while (count-- > 0) { offset = GET2(slot, 0) << 1; GET_LOCAL_BASE(TMP2, 0, OVECTOR(offset)); add_jump(compiler, &found, CMP(SLJIT_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0)); slot += common->name_entry_size; } offset = GET2(slot, 0) << 1; GET_LOCAL_BASE(TMP2, 0, OVECTOR(offset)); if (backtracks != NULL && !common->jscript_compat) add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0)); set_jumps(found, LABEL()); } static void compile_ref_matchingpath(compiler_common *common, pcre_uchar *cc, jump_list **backtracks, BOOL withchecks, BOOL emptyfail) { DEFINE_COMPILER; BOOL ref = (*cc == OP_REF || *cc == OP_REFI); int offset = 0; struct sljit_jump *jump = NULL; struct sljit_jump *partial; struct sljit_jump *nopartial; if (ref) { offset = GET2(cc, 1) << 1; OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); /* OVECTOR(1) contains the "string begin - 1" constant. */ if (withchecks && !common->jscript_compat) add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); } else OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); #if defined SUPPORT_UTF && defined SUPPORT_UCP if (common->utf && *cc == OP_REFI) { SLJIT_ASSERT(TMP1 == SLJIT_R0 && STACK_TOP == SLJIT_R1); if (ref) OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); else OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); if (withchecks) jump = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_R2, 0); /* No free saved registers so save data on stack. */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); OP1(SLJIT_MOV, SLJIT_R1, 0, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_R3, 0, STR_END, 0); sljit_emit_icall(compiler, SLJIT_CALL, SLJIT_RET(SW) | SLJIT_ARG1(SW) | SLJIT_ARG2(SW) | SLJIT_ARG3(SW) | SLJIT_ARG4(SW), SLJIT_IMM, SLJIT_FUNC_OFFSET(do_utf_caselesscmp)); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_RETURN_REG, 0); if (common->mode == JIT_COMPILE) add_jump(compiler, backtracks, CMP(SLJIT_LESS_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1)); else { OP2(SLJIT_SUB | SLJIT_SET_Z | SLJIT_SET_LESS, SLJIT_UNUSED, 0, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1); add_jump(compiler, backtracks, JUMP(SLJIT_LESS)); nopartial = JUMP(SLJIT_NOT_EQUAL); OP1(SLJIT_MOV, STR_PTR, 0, STR_END, 0); check_partial(common, FALSE); add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(nopartial); } } else #endif /* SUPPORT_UTF && SUPPORT_UCP */ { if (ref) OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP1, 0); else OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw), TMP1, 0); if (withchecks) jump = JUMP(SLJIT_ZERO); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); partial = CMP(SLJIT_GREATER, STR_PTR, 0, STR_END, 0); if (common->mode == JIT_COMPILE) add_jump(compiler, backtracks, partial); add_jump(compiler, *cc == OP_REF ? &common->casefulcmp : &common->caselesscmp, JUMP(SLJIT_FAST_CALL)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); if (common->mode != JIT_COMPILE) { nopartial = JUMP(SLJIT_JUMP); JUMPHERE(partial); /* TMP2 -= STR_END - STR_PTR */ OP2(SLJIT_SUB, TMP2, 0, TMP2, 0, STR_PTR, 0); OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, STR_END, 0); partial = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, 0); OP1(SLJIT_MOV, STR_PTR, 0, STR_END, 0); add_jump(compiler, *cc == OP_REF ? &common->casefulcmp : &common->caselesscmp, JUMP(SLJIT_FAST_CALL)); add_jump(compiler, backtracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); JUMPHERE(partial); check_partial(common, FALSE); add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); JUMPHERE(nopartial); } } if (jump != NULL) { if (emptyfail) add_jump(compiler, backtracks, jump); else JUMPHERE(jump); } } static SLJIT_INLINE pcre_uchar *compile_ref_iterator_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; BOOL ref = (*cc == OP_REF || *cc == OP_REFI); backtrack_common *backtrack; pcre_uchar type; int offset = 0; struct sljit_label *label; struct sljit_jump *zerolength; struct sljit_jump *jump = NULL; pcre_uchar *ccbegin = cc; int min = 0, max = 0; BOOL minimize; PUSH_BACKTRACK(sizeof(ref_iterator_backtrack), cc, NULL); if (ref) offset = GET2(cc, 1) << 1; else cc += IMM2_SIZE; type = cc[1 + IMM2_SIZE]; SLJIT_COMPILE_ASSERT((OP_CRSTAR & 0x1) == 0, crstar_opcode_must_be_even); minimize = (type & 0x1) != 0; switch(type) { case OP_CRSTAR: case OP_CRMINSTAR: min = 0; max = 0; cc += 1 + IMM2_SIZE + 1; break; case OP_CRPLUS: case OP_CRMINPLUS: min = 1; max = 0; cc += 1 + IMM2_SIZE + 1; break; case OP_CRQUERY: case OP_CRMINQUERY: min = 0; max = 1; cc += 1 + IMM2_SIZE + 1; break; case OP_CRRANGE: case OP_CRMINRANGE: min = GET2(cc, 1 + IMM2_SIZE + 1); max = GET2(cc, 1 + IMM2_SIZE + 1 + IMM2_SIZE); cc += 1 + IMM2_SIZE + 1 + 2 * IMM2_SIZE; break; default: SLJIT_UNREACHABLE(); break; } if (!minimize) { if (min == 0) { allocate_stack(common, 2); if (ref) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); /* Temporary release of STR_PTR. */ OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); /* Handles both invalid and empty cases. Since the minimum repeat, is zero the invalid case is basically the same as an empty case. */ if (ref) zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); else { compile_dnref_search(common, ccbegin, NULL); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, TMP2, 0); zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); } /* Restore if not zero length. */ OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); } else { allocate_stack(common, 1); if (ref) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); if (ref) { add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); } else { compile_dnref_search(common, ccbegin, &backtrack->topbacktracks); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, TMP2, 0); zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); } } if (min > 1 || max > 1) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, SLJIT_IMM, 0); label = LABEL(); if (!ref) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1); compile_ref_matchingpath(common, ccbegin, &backtrack->topbacktracks, FALSE, FALSE); if (min > 1 || max > 1) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, TMP1, 0); if (min > 1) CMPTO(SLJIT_LESS, TMP1, 0, SLJIT_IMM, min, label); if (max > 1) { jump = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, max); allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); JUMPTO(SLJIT_JUMP, label); JUMPHERE(jump); } } if (max == 0) { /* Includes min > 1 case as well. */ allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); JUMPTO(SLJIT_JUMP, label); } JUMPHERE(zerolength); BACKTRACK_AS(ref_iterator_backtrack)->matchingpath = LABEL(); count_match(common); return cc; } allocate_stack(common, ref ? 2 : 3); if (ref) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); if (type != OP_CRMINSTAR) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); if (min == 0) { /* Handles both invalid and empty cases. Since the minimum repeat, is zero the invalid case is basically the same as an empty case. */ if (ref) zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); else { compile_dnref_search(common, ccbegin, NULL); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0); zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); } /* Length is non-zero, we can match real repeats. */ OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); jump = JUMP(SLJIT_JUMP); } else { if (ref) { add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); } else { compile_dnref_search(common, ccbegin, &backtrack->topbacktracks); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0); zerolength = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); } } BACKTRACK_AS(ref_iterator_backtrack)->matchingpath = LABEL(); if (max > 0) add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_GREATER_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, max)); if (!ref) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); compile_ref_matchingpath(common, ccbegin, &backtrack->topbacktracks, TRUE, TRUE); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); if (min > 1) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); CMPTO(SLJIT_LESS, TMP1, 0, SLJIT_IMM, min, BACKTRACK_AS(ref_iterator_backtrack)->matchingpath); } else if (max > 0) OP2(SLJIT_ADD, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 1); if (jump != NULL) JUMPHERE(jump); JUMPHERE(zerolength); count_match(common); return cc; } static SLJIT_INLINE pcre_uchar *compile_recurse_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; recurse_entry *entry = common->entries; recurse_entry *prev = NULL; sljit_sw start = GET(cc, 1); pcre_uchar *start_cc; BOOL needs_control_head; PUSH_BACKTRACK(sizeof(recurse_backtrack), cc, NULL); /* Inlining simple patterns. */ if (get_framesize(common, common->start + start, NULL, TRUE, &needs_control_head) == no_stack) { start_cc = common->start + start; compile_matchingpath(common, next_opcode(common, start_cc), bracketend(start_cc) - (1 + LINK_SIZE), backtrack); BACKTRACK_AS(recurse_backtrack)->inlined_pattern = TRUE; return cc + 1 + LINK_SIZE; } while (entry != NULL) { if (entry->start == start) break; prev = entry; entry = entry->next; } if (entry == NULL) { entry = sljit_alloc_memory(compiler, sizeof(recurse_entry)); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return NULL; entry->next = NULL; entry->entry = NULL; entry->calls = NULL; entry->start = start; if (prev != NULL) prev->next = entry; else common->entries = entry; } if (common->has_set_som && common->mark_ptr != 0) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); allocate_stack(common, 2); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); } else if (common->has_set_som || common->mark_ptr != 0) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->has_set_som ? (int)(OVECTOR(0)) : common->mark_ptr); allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); } if (entry->entry == NULL) add_jump(compiler, &entry->calls, JUMP(SLJIT_FAST_CALL)); else JUMPTO(SLJIT_FAST_CALL, entry->entry); /* Leave if the match is failed. */ add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0)); return cc + 1 + LINK_SIZE; } static sljit_s32 SLJIT_FUNC do_callout(struct jit_arguments *arguments, PUBL(callout_block) *callout_block, pcre_uchar **jit_ovector) { const pcre_uchar *begin = arguments->begin; int *offset_vector = arguments->offsets; int offset_count = arguments->offset_count; int i; if (PUBL(callout) == NULL) return 0; callout_block->version = 2; callout_block->callout_data = arguments->callout_data; /* Offsets in subject. */ callout_block->subject_length = arguments->end - arguments->begin; callout_block->start_match = (pcre_uchar*)callout_block->subject - arguments->begin; callout_block->current_position = (pcre_uchar*)callout_block->offset_vector - arguments->begin; #if defined COMPILE_PCRE8 callout_block->subject = (PCRE_SPTR)begin; #elif defined COMPILE_PCRE16 callout_block->subject = (PCRE_SPTR16)begin; #elif defined COMPILE_PCRE32 callout_block->subject = (PCRE_SPTR32)begin; #endif /* Convert and copy the JIT offset vector to the offset_vector array. */ callout_block->capture_top = 0; callout_block->offset_vector = offset_vector; for (i = 2; i < offset_count; i += 2) { offset_vector[i] = jit_ovector[i] - begin; offset_vector[i + 1] = jit_ovector[i + 1] - begin; if (jit_ovector[i] >= begin) callout_block->capture_top = i; } callout_block->capture_top = (callout_block->capture_top >> 1) + 1; if (offset_count > 0) offset_vector[0] = -1; if (offset_count > 1) offset_vector[1] = -1; return (*PUBL(callout))(callout_block); } /* Aligning to 8 byte. */ #define CALLOUT_ARG_SIZE \ (((int)sizeof(PUBL(callout_block)) + 7) & ~7) #define CALLOUT_ARG_OFFSET(arg) \ SLJIT_OFFSETOF(PUBL(callout_block), arg) static SLJIT_INLINE pcre_uchar *compile_callout_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); allocate_stack(common, CALLOUT_ARG_SIZE / sizeof(sljit_sw)); SLJIT_ASSERT(common->capture_last_ptr != 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV_S32, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(callout_number), SLJIT_IMM, cc[1]); OP1(SLJIT_MOV_S32, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(capture_last), TMP2, 0); /* These pointer sized fields temporarly stores internal variables. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(offset_vector), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(subject), TMP2, 0); if (common->mark_ptr != 0) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr)); OP1(SLJIT_MOV_S32, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(pattern_position), SLJIT_IMM, GET(cc, 2)); OP1(SLJIT_MOV_S32, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(next_item_length), SLJIT_IMM, GET(cc, 2 + LINK_SIZE)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(mark), (common->mark_ptr != 0) ? TMP2 : SLJIT_IMM, 0); /* Needed to save important temporary registers. */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); /* SLJIT_R0 = arguments */ OP1(SLJIT_MOV, SLJIT_R1, 0, STACK_TOP, 0); GET_LOCAL_BASE(SLJIT_R2, 0, OVECTOR_START); sljit_emit_icall(compiler, SLJIT_CALL, SLJIT_RET(S32) | SLJIT_ARG1(SW) | SLJIT_ARG2(SW) | SLJIT_ARG3(SW), SLJIT_IMM, SLJIT_FUNC_OFFSET(do_callout)); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); free_stack(common, CALLOUT_ARG_SIZE / sizeof(sljit_sw)); /* Check return value. */ OP2(SLJIT_SUB32 | SLJIT_SET_Z | SLJIT_SET_SIG_GREATER, SLJIT_UNUSED, 0, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0); add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_SIG_GREATER32)); if (common->forced_quit_label == NULL) add_jump(compiler, &common->forced_quit, JUMP(SLJIT_NOT_EQUAL32) /* SIG_LESS */); else JUMPTO(SLJIT_NOT_EQUAL32 /* SIG_LESS */, common->forced_quit_label); return cc + 2 + 2 * LINK_SIZE; } #undef CALLOUT_ARG_SIZE #undef CALLOUT_ARG_OFFSET static SLJIT_INLINE BOOL assert_needs_str_ptr_saving(pcre_uchar *cc) { while (TRUE) { switch (*cc) { case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_CIRC: case OP_CIRCM: case OP_DOLL: case OP_DOLLM: case OP_CALLOUT: case OP_ALT: cc += PRIV(OP_lengths)[*cc]; break; case OP_KET: return FALSE; default: return TRUE; } } } static pcre_uchar *compile_assert_matchingpath(compiler_common *common, pcre_uchar *cc, assert_backtrack *backtrack, BOOL conditional) { DEFINE_COMPILER; int framesize; int extrasize; BOOL needs_control_head; int private_data_ptr; backtrack_common altbacktrack; pcre_uchar *ccbegin; pcre_uchar opcode; pcre_uchar bra = OP_BRA; jump_list *tmp = NULL; jump_list **target = (conditional) ? &backtrack->condfailed : &backtrack->common.topbacktracks; jump_list **found; /* Saving previous accept variables. */ BOOL save_local_exit = common->local_exit; BOOL save_positive_assert = common->positive_assert; then_trap_backtrack *save_then_trap = common->then_trap; struct sljit_label *save_quit_label = common->quit_label; struct sljit_label *save_accept_label = common->accept_label; jump_list *save_quit = common->quit; jump_list *save_positive_assert_quit = common->positive_assert_quit; jump_list *save_accept = common->accept; struct sljit_jump *jump; struct sljit_jump *brajump = NULL; /* Assert captures then. */ common->then_trap = NULL; if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) { SLJIT_ASSERT(!conditional); bra = *cc; cc++; } private_data_ptr = PRIVATE_DATA(cc); SLJIT_ASSERT(private_data_ptr != 0); framesize = get_framesize(common, cc, NULL, FALSE, &needs_control_head); backtrack->framesize = framesize; backtrack->private_data_ptr = private_data_ptr; opcode = *cc; SLJIT_ASSERT(opcode >= OP_ASSERT && opcode <= OP_ASSERTBACK_NOT); found = (opcode == OP_ASSERT || opcode == OP_ASSERTBACK) ? &tmp : target; ccbegin = cc; cc += GET(cc, 1); if (bra == OP_BRAMINZERO) { /* This is a braminzero backtrack path. */ OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); brajump = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); } if (framesize < 0) { extrasize = 1; if (bra == OP_BRA && !assert_needs_str_ptr_saving(ccbegin + 1 + LINK_SIZE)) extrasize = 0; if (needs_control_head) extrasize++; if (framesize == no_frame) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); if (extrasize > 0) allocate_stack(common, extrasize); if (needs_control_head) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); if (extrasize > 0) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); if (needs_control_head) { SLJIT_ASSERT(extrasize == 2); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); } } else { extrasize = needs_control_head ? 3 : 2; allocate_stack(common, framesize + extrasize); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP2(SLJIT_ADD, TMP2, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + extrasize) * sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); if (needs_control_head) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); if (needs_control_head) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); } else OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); init_frame(common, ccbegin, NULL, framesize + extrasize - 1, extrasize, FALSE); } memset(&altbacktrack, 0, sizeof(backtrack_common)); if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) { /* Negative assert is stronger than positive assert. */ common->local_exit = TRUE; common->quit_label = NULL; common->quit = NULL; common->positive_assert = FALSE; } else common->positive_assert = TRUE; common->positive_assert_quit = NULL; while (1) { common->accept_label = NULL; common->accept = NULL; altbacktrack.top = NULL; altbacktrack.topbacktracks = NULL; if (*ccbegin == OP_ALT && extrasize > 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); altbacktrack.cc = ccbegin; compile_matchingpath(common, ccbegin + 1 + LINK_SIZE, cc, &altbacktrack); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) { if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) { common->local_exit = save_local_exit; common->quit_label = save_quit_label; common->quit = save_quit; } common->positive_assert = save_positive_assert; common->then_trap = save_then_trap; common->accept_label = save_accept_label; common->positive_assert_quit = save_positive_assert_quit; common->accept = save_accept; return NULL; } common->accept_label = LABEL(); if (common->accept != NULL) set_jumps(common->accept, common->accept_label); /* Reset stack. */ if (framesize < 0) { if (framesize == no_frame) OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); else if (extrasize > 0) free_stack(common, extrasize); if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(-1)); } else { if ((opcode != OP_ASSERT_NOT && opcode != OP_ASSERTBACK_NOT) || conditional) { /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ OP2(SLJIT_SUB, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 1) * sizeof(sljit_sw)); if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(-1)); } else { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(-framesize - 2)); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); } } if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) { /* We know that STR_PTR was stored on the top of the stack. */ if (conditional) { if (extrasize > 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), needs_control_head ? STACK(-2) : STACK(-1)); } else if (bra == OP_BRAZERO) { if (framesize < 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(-extrasize)); else { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(-framesize - 1)); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(-framesize - extrasize)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); } OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } else if (framesize >= 0) { /* For OP_BRA and OP_BRAMINZERO. */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-framesize - 1)); } } add_jump(compiler, found, JUMP(SLJIT_JUMP)); compile_backtrackingpath(common, altbacktrack.top); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) { if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) { common->local_exit = save_local_exit; common->quit_label = save_quit_label; common->quit = save_quit; } common->positive_assert = save_positive_assert; common->then_trap = save_then_trap; common->accept_label = save_accept_label; common->positive_assert_quit = save_positive_assert_quit; common->accept = save_accept; return NULL; } set_jumps(altbacktrack.topbacktracks, LABEL()); if (*cc != OP_ALT) break; ccbegin = cc; cc += GET(cc, 1); } if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) { SLJIT_ASSERT(common->positive_assert_quit == NULL); /* Makes the check less complicated below. */ common->positive_assert_quit = common->quit; } /* None of them matched. */ if (common->positive_assert_quit != NULL) { jump = JUMP(SLJIT_JUMP); set_jumps(common->positive_assert_quit, LABEL()); SLJIT_ASSERT(framesize != no_stack); if (framesize < 0) OP2(SLJIT_SUB, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, extrasize * sizeof(sljit_sw)); else { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + extrasize) * sizeof(sljit_sw)); } JUMPHERE(jump); } if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(1)); if (opcode == OP_ASSERT || opcode == OP_ASSERTBACK) { /* Assert is failed. */ if ((conditional && extrasize > 0) || bra == OP_BRAZERO) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); if (framesize < 0) { /* The topmost item should be 0. */ if (bra == OP_BRAZERO) { if (extrasize == 2) free_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } else if (extrasize > 0) free_stack(common, extrasize); } else { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(extrasize - 1)); /* The topmost item should be 0. */ if (bra == OP_BRAZERO) { free_stack(common, framesize + extrasize - 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } else free_stack(common, framesize + extrasize); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); } jump = JUMP(SLJIT_JUMP); if (bra != OP_BRAZERO) add_jump(compiler, target, jump); /* Assert is successful. */ set_jumps(tmp, LABEL()); if (framesize < 0) { /* We know that STR_PTR was stored on the top of the stack. */ if (extrasize > 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(-extrasize)); /* Keep the STR_PTR on the top of the stack. */ if (bra == OP_BRAZERO) { OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); if (extrasize == 2) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); } else if (bra == OP_BRAMINZERO) { OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } } else { if (bra == OP_BRA) { /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ OP2(SLJIT_SUB, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 1) * sizeof(sljit_sw)); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(-extrasize + 1)); } else { /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ OP2(SLJIT_SUB, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 2) * sizeof(sljit_sw)); if (extrasize == 2) { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); if (bra == OP_BRAMINZERO) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } else { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), bra == OP_BRAZERO ? STR_PTR : SLJIT_IMM, 0); } } } if (bra == OP_BRAZERO) { backtrack->matchingpath = LABEL(); SET_LABEL(jump, backtrack->matchingpath); } else if (bra == OP_BRAMINZERO) { JUMPTO(SLJIT_JUMP, backtrack->matchingpath); JUMPHERE(brajump); if (framesize >= 0) { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-framesize - 1)); } set_jumps(backtrack->common.topbacktracks, LABEL()); } } else { /* AssertNot is successful. */ if (framesize < 0) { if (extrasize > 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); if (bra != OP_BRA) { if (extrasize == 2) free_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } else if (extrasize > 0) free_stack(common, extrasize); } else { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(extrasize - 1)); /* The topmost item should be 0. */ if (bra != OP_BRA) { free_stack(common, framesize + extrasize - 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } else free_stack(common, framesize + extrasize); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); } if (bra == OP_BRAZERO) backtrack->matchingpath = LABEL(); else if (bra == OP_BRAMINZERO) { JUMPTO(SLJIT_JUMP, backtrack->matchingpath); JUMPHERE(brajump); } if (bra != OP_BRA) { SLJIT_ASSERT(found == &backtrack->common.topbacktracks); set_jumps(backtrack->common.topbacktracks, LABEL()); backtrack->common.topbacktracks = NULL; } } if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) { common->local_exit = save_local_exit; common->quit_label = save_quit_label; common->quit = save_quit; } common->positive_assert = save_positive_assert; common->then_trap = save_then_trap; common->accept_label = save_accept_label; common->positive_assert_quit = save_positive_assert_quit; common->accept = save_accept; return cc + 1 + LINK_SIZE; } static SLJIT_INLINE void match_once_common(compiler_common *common, pcre_uchar ket, int framesize, int private_data_ptr, BOOL has_alternatives, BOOL needs_control_head) { DEFINE_COMPILER; int stacksize; if (framesize < 0) { if (framesize == no_frame) OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); else { stacksize = needs_control_head ? 1 : 0; if (ket != OP_KET || has_alternatives) stacksize++; if (stacksize > 0) free_stack(common, stacksize); } if (needs_control_head) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), (ket != OP_KET || has_alternatives) ? STACK(-2) : STACK(-1)); /* TMP2 which is set here used by OP_KETRMAX below. */ if (ket == OP_KETRMAX) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(-1)); else if (ket == OP_KETRMIN) { /* Move the STR_PTR to the private_data_ptr. */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-1)); } } else { stacksize = (ket != OP_KET || has_alternatives) ? 2 : 1; OP2(SLJIT_SUB, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + stacksize) * sizeof(sljit_sw)); if (needs_control_head) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(-1)); if (ket == OP_KETRMAX) { /* TMP2 which is set here used by OP_KETRMAX below. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); } } if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP1, 0); } static SLJIT_INLINE int match_capture_common(compiler_common *common, int stacksize, int offset, int private_data_ptr) { DEFINE_COMPILER; if (common->capture_last_ptr != 0) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); stacksize++; } if (common->optimized_cbracket[offset >> 1] == 0) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize + 1), TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); stacksize += 2; } return stacksize; } /* Handling bracketed expressions is probably the most complex part. Stack layout naming characters: S - Push the current STR_PTR 0 - Push a 0 (NULL) A - Push the current STR_PTR. Needed for restoring the STR_PTR before the next alternative. Not pushed if there are no alternatives. M - Any values pushed by the current alternative. Can be empty, or anything. C - Push the previous OVECTOR(i), OVECTOR(i+1) and OVECTOR_PRIV(i) to the stack. L - Push the previous local (pointed by localptr) to the stack () - opional values stored on the stack ()* - optonal, can be stored multiple times The following list shows the regular expression templates, their PCRE byte codes and stack layout supported by pcre-sljit. (?:) OP_BRA | OP_KET A M () OP_CBRA | OP_KET C M (?:)+ OP_BRA | OP_KETRMAX 0 A M S ( A M S )* OP_SBRA | OP_KETRMAX 0 L M S ( L M S )* (?:)+? OP_BRA | OP_KETRMIN 0 A M S ( A M S )* OP_SBRA | OP_KETRMIN 0 L M S ( L M S )* ()+ OP_CBRA | OP_KETRMAX 0 C M S ( C M S )* OP_SCBRA | OP_KETRMAX 0 C M S ( C M S )* ()+? OP_CBRA | OP_KETRMIN 0 C M S ( C M S )* OP_SCBRA | OP_KETRMIN 0 C M S ( C M S )* (?:)? OP_BRAZERO | OP_BRA | OP_KET S ( A M 0 ) (?:)?? OP_BRAMINZERO | OP_BRA | OP_KET S ( A M 0 ) ()? OP_BRAZERO | OP_CBRA | OP_KET S ( C M 0 ) ()?? OP_BRAMINZERO | OP_CBRA | OP_KET S ( C M 0 ) (?:)* OP_BRAZERO | OP_BRA | OP_KETRMAX S 0 ( A M S )* OP_BRAZERO | OP_SBRA | OP_KETRMAX S 0 ( L M S )* (?:)*? OP_BRAMINZERO | OP_BRA | OP_KETRMIN S 0 ( A M S )* OP_BRAMINZERO | OP_SBRA | OP_KETRMIN S 0 ( L M S )* ()* OP_BRAZERO | OP_CBRA | OP_KETRMAX S 0 ( C M S )* OP_BRAZERO | OP_SCBRA | OP_KETRMAX S 0 ( C M S )* ()*? OP_BRAMINZERO | OP_CBRA | OP_KETRMIN S 0 ( C M S )* OP_BRAMINZERO | OP_SCBRA | OP_KETRMIN S 0 ( C M S )* Stack layout naming characters: A - Push the alternative index (starting from 0) on the stack. Not pushed if there is no alternatives. M - Any values pushed by the current alternative. Can be empty, or anything. The next list shows the possible content of a bracket: (|) OP_*BRA | OP_ALT ... M A (?()|) OP_*COND | OP_ALT M A (?>|) OP_ONCE | OP_ALT ... [stack trace] M A (?>|) OP_ONCE_NC | OP_ALT ... [stack trace] M A Or nothing, if trace is unnecessary */ static pcre_uchar *compile_bracket_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; pcre_uchar opcode; int private_data_ptr = 0; int offset = 0; int i, stacksize; int repeat_ptr = 0, repeat_length = 0; int repeat_type = 0, repeat_count = 0; pcre_uchar *ccbegin; pcre_uchar *matchingpath; pcre_uchar *slot; pcre_uchar bra = OP_BRA; pcre_uchar ket; assert_backtrack *assert; BOOL has_alternatives; BOOL needs_control_head = FALSE; struct sljit_jump *jump; struct sljit_jump *skip; struct sljit_label *rmax_label = NULL; struct sljit_jump *braminzero = NULL; PUSH_BACKTRACK(sizeof(bracket_backtrack), cc, NULL); if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) { bra = *cc; cc++; opcode = *cc; } opcode = *cc; ccbegin = cc; matchingpath = bracketend(cc) - 1 - LINK_SIZE; ket = *matchingpath; if (ket == OP_KET && PRIVATE_DATA(matchingpath) != 0) { repeat_ptr = PRIVATE_DATA(matchingpath); repeat_length = PRIVATE_DATA(matchingpath + 1); repeat_type = PRIVATE_DATA(matchingpath + 2); repeat_count = PRIVATE_DATA(matchingpath + 3); SLJIT_ASSERT(repeat_length != 0 && repeat_type != 0 && repeat_count != 0); if (repeat_type == OP_UPTO) ket = OP_KETRMAX; if (repeat_type == OP_MINUPTO) ket = OP_KETRMIN; } if ((opcode == OP_COND || opcode == OP_SCOND) && cc[1 + LINK_SIZE] == OP_DEF) { /* Drop this bracket_backtrack. */ parent->top = backtrack->prev; return matchingpath + 1 + LINK_SIZE + repeat_length; } matchingpath = ccbegin + 1 + LINK_SIZE; SLJIT_ASSERT(ket == OP_KET || ket == OP_KETRMAX || ket == OP_KETRMIN); SLJIT_ASSERT(!((bra == OP_BRAZERO && ket == OP_KETRMIN) || (bra == OP_BRAMINZERO && ket == OP_KETRMAX))); cc += GET(cc, 1); has_alternatives = *cc == OP_ALT; if (SLJIT_UNLIKELY(opcode == OP_COND || opcode == OP_SCOND)) has_alternatives = (*matchingpath == OP_RREF || *matchingpath == OP_DNRREF || *matchingpath == OP_FAIL) ? FALSE : TRUE; if (SLJIT_UNLIKELY(opcode == OP_COND) && (*cc == OP_KETRMAX || *cc == OP_KETRMIN)) opcode = OP_SCOND; if (SLJIT_UNLIKELY(opcode == OP_ONCE_NC)) opcode = OP_ONCE; if (opcode == OP_CBRA || opcode == OP_SCBRA) { /* Capturing brackets has a pre-allocated space. */ offset = GET2(ccbegin, 1 + LINK_SIZE); if (common->optimized_cbracket[offset] == 0) { private_data_ptr = OVECTOR_PRIV(offset); offset <<= 1; } else { offset <<= 1; private_data_ptr = OVECTOR(offset); } BACKTRACK_AS(bracket_backtrack)->private_data_ptr = private_data_ptr; matchingpath += IMM2_SIZE; } else if (opcode == OP_ONCE || opcode == OP_SBRA || opcode == OP_SCOND) { /* Other brackets simply allocate the next entry. */ private_data_ptr = PRIVATE_DATA(ccbegin); SLJIT_ASSERT(private_data_ptr != 0); BACKTRACK_AS(bracket_backtrack)->private_data_ptr = private_data_ptr; if (opcode == OP_ONCE) BACKTRACK_AS(bracket_backtrack)->u.framesize = get_framesize(common, ccbegin, NULL, FALSE, &needs_control_head); } /* Instructions before the first alternative. */ stacksize = 0; if (ket == OP_KETRMAX || (ket == OP_KETRMIN && bra != OP_BRAMINZERO)) stacksize++; if (bra == OP_BRAZERO) stacksize++; if (stacksize > 0) allocate_stack(common, stacksize); stacksize = 0; if (ket == OP_KETRMAX || (ket == OP_KETRMIN && bra != OP_BRAMINZERO)) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); stacksize++; } if (bra == OP_BRAZERO) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); if (bra == OP_BRAMINZERO) { /* This is a backtrack path! (Since the try-path of OP_BRAMINZERO matches to the empty string) */ OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); if (ket != OP_KETRMIN) { free_stack(common, 1); braminzero = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); } else { if (opcode == OP_ONCE || opcode >= OP_SBRA) { jump = CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); /* Nothing stored during the first run. */ skip = JUMP(SLJIT_JUMP); JUMPHERE(jump); /* Checking zero-length iteration. */ if (opcode != OP_ONCE || BACKTRACK_AS(bracket_backtrack)->u.framesize < 0) { /* When we come from outside, private_data_ptr contains the previous STR_PTR. */ braminzero = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); } else { /* Except when the whole stack frame must be saved. */ OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); braminzero = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_MEM1(TMP1), STACK(-BACKTRACK_AS(bracket_backtrack)->u.framesize - 2)); } JUMPHERE(skip); } else { jump = CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); JUMPHERE(jump); } } } if (repeat_type != 0) { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, repeat_count); if (repeat_type == OP_EXACT) rmax_label = LABEL(); } if (ket == OP_KETRMIN) BACKTRACK_AS(bracket_backtrack)->recursive_matchingpath = LABEL(); if (ket == OP_KETRMAX) { rmax_label = LABEL(); if (has_alternatives && opcode != OP_ONCE && opcode < OP_SBRA && repeat_type == 0) BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = rmax_label; } /* Handling capturing brackets and alternatives. */ if (opcode == OP_ONCE) { stacksize = 0; if (needs_control_head) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); stacksize++; } if (BACKTRACK_AS(bracket_backtrack)->u.framesize < 0) { /* Neither capturing brackets nor recursions are found in the block. */ if (ket == OP_KETRMIN) { stacksize += 2; if (!needs_control_head) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); } else { if (BACKTRACK_AS(bracket_backtrack)->u.framesize == no_frame) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); if (ket == OP_KETRMAX || has_alternatives) stacksize++; } if (stacksize > 0) allocate_stack(common, stacksize); stacksize = 0; if (needs_control_head) { stacksize++; OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); } if (ket == OP_KETRMIN) { if (needs_control_head) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); if (BACKTRACK_AS(bracket_backtrack)->u.framesize == no_frame) OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0, SLJIT_IMM, needs_control_head ? (2 * sizeof(sljit_sw)) : sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize + 1), TMP2, 0); } else if (ket == OP_KETRMAX || has_alternatives) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); } else { if (ket != OP_KET || has_alternatives) stacksize++; stacksize += BACKTRACK_AS(bracket_backtrack)->u.framesize + 1; allocate_stack(common, stacksize); if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP2(SLJIT_ADD, TMP2, 0, STACK_TOP, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); stacksize = needs_control_head ? 1 : 0; if (ket != OP_KET || has_alternatives) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); stacksize++; OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); } else { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); } init_frame(common, ccbegin, NULL, BACKTRACK_AS(bracket_backtrack)->u.framesize + stacksize, stacksize + 1, FALSE); } } else if (opcode == OP_CBRA || opcode == OP_SCBRA) { /* Saving the previous values. */ if (common->optimized_cbracket[offset >> 1] != 0) { SLJIT_ASSERT(private_data_ptr == OVECTOR(offset)); allocate_stack(common, 2); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr + sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); } else { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); } } else if (opcode == OP_SBRA || opcode == OP_SCOND) { /* Saving the previous value. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); } else if (has_alternatives) { /* Pushing the starting string pointer. */ allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); } /* Generating code for the first alternative. */ if (opcode == OP_COND || opcode == OP_SCOND) { if (*matchingpath == OP_CREF) { SLJIT_ASSERT(has_alternatives); add_jump(compiler, &(BACKTRACK_AS(bracket_backtrack)->u.condfailed), CMP(SLJIT_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(matchingpath, 1) << 1), SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); matchingpath += 1 + IMM2_SIZE; } else if (*matchingpath == OP_DNCREF) { SLJIT_ASSERT(has_alternatives); i = GET2(matchingpath, 1 + IMM2_SIZE); slot = common->name_table + GET2(matchingpath, 1) * common->name_entry_size; OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(slot, 0) << 1), TMP1, 0); slot += common->name_entry_size; i--; while (i-- > 0) { OP2(SLJIT_SUB, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(slot, 0) << 1), TMP1, 0); OP2(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, TMP2, 0, STR_PTR, 0); slot += common->name_entry_size; } OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); add_jump(compiler, &(BACKTRACK_AS(bracket_backtrack)->u.condfailed), JUMP(SLJIT_ZERO)); matchingpath += 1 + 2 * IMM2_SIZE; } else if (*matchingpath == OP_RREF || *matchingpath == OP_DNRREF || *matchingpath == OP_FAIL) { /* Never has other case. */ BACKTRACK_AS(bracket_backtrack)->u.condfailed = NULL; SLJIT_ASSERT(!has_alternatives); if (*matchingpath == OP_FAIL) stacksize = 0; else if (*matchingpath == OP_RREF) { stacksize = GET2(matchingpath, 1); if (common->currententry == NULL) stacksize = 0; else if (stacksize == RREF_ANY) stacksize = 1; else if (common->currententry->start == 0) stacksize = stacksize == 0; else stacksize = stacksize == (int)GET2(common->start, common->currententry->start + 1 + LINK_SIZE); if (stacksize != 0) matchingpath += 1 + IMM2_SIZE; } else { if (common->currententry == NULL || common->currententry->start == 0) stacksize = 0; else { stacksize = GET2(matchingpath, 1 + IMM2_SIZE); slot = common->name_table + GET2(matchingpath, 1) * common->name_entry_size; i = (int)GET2(common->start, common->currententry->start + 1 + LINK_SIZE); while (stacksize > 0) { if ((int)GET2(slot, 0) == i) break; slot += common->name_entry_size; stacksize--; } } if (stacksize != 0) matchingpath += 1 + 2 * IMM2_SIZE; } /* The stacksize == 0 is a common "else" case. */ if (stacksize == 0) { if (*cc == OP_ALT) { matchingpath = cc + 1 + LINK_SIZE; cc += GET(cc, 1); } else matchingpath = cc; } } else { SLJIT_ASSERT(has_alternatives && *matchingpath >= OP_ASSERT && *matchingpath <= OP_ASSERTBACK_NOT); /* Similar code as PUSH_BACKTRACK macro. */ assert = sljit_alloc_memory(compiler, sizeof(assert_backtrack)); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return NULL; memset(assert, 0, sizeof(assert_backtrack)); assert->common.cc = matchingpath; BACKTRACK_AS(bracket_backtrack)->u.assert = assert; matchingpath = compile_assert_matchingpath(common, matchingpath, assert, TRUE); } } compile_matchingpath(common, matchingpath, cc, backtrack); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return NULL; if (opcode == OP_ONCE) match_once_common(common, ket, BACKTRACK_AS(bracket_backtrack)->u.framesize, private_data_ptr, has_alternatives, needs_control_head); stacksize = 0; if (repeat_type == OP_MINUPTO) { /* We need to preserve the counter. TMP2 will be used below. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); stacksize++; } if (ket != OP_KET || bra != OP_BRA) stacksize++; if (offset != 0) { if (common->capture_last_ptr != 0) stacksize++; if (common->optimized_cbracket[offset >> 1] == 0) stacksize += 2; } if (has_alternatives && opcode != OP_ONCE) stacksize++; if (stacksize > 0) allocate_stack(common, stacksize); stacksize = 0; if (repeat_type == OP_MINUPTO) { /* TMP2 was set above. */ OP2(SLJIT_SUB, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP2, 0, SLJIT_IMM, 1); stacksize++; } if (ket != OP_KET || bra != OP_BRA) { if (ket != OP_KET) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); else OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); stacksize++; } if (offset != 0) stacksize = match_capture_common(common, stacksize, offset, private_data_ptr); if (has_alternatives) { if (opcode != OP_ONCE) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); if (ket != OP_KETRMAX) BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); } /* Must be after the matchingpath label. */ if (offset != 0 && common->optimized_cbracket[offset >> 1] != 0) { SLJIT_ASSERT(private_data_ptr == OVECTOR(offset + 0)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); } if (ket == OP_KETRMAX) { if (repeat_type != 0) { if (has_alternatives) BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, rmax_label); /* Drop STR_PTR for greedy plus quantifier. */ if (opcode != OP_ONCE) free_stack(common, 1); } else if (opcode == OP_ONCE || opcode >= OP_SBRA) { if (has_alternatives) BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); /* Checking zero-length iteration. */ if (opcode != OP_ONCE) { CMPTO(SLJIT_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0, rmax_label); /* Drop STR_PTR for greedy plus quantifier. */ if (bra != OP_BRAZERO) free_stack(common, 1); } else /* TMP2 must contain the starting STR_PTR. */ CMPTO(SLJIT_NOT_EQUAL, TMP2, 0, STR_PTR, 0, rmax_label); } else JUMPTO(SLJIT_JUMP, rmax_label); BACKTRACK_AS(bracket_backtrack)->recursive_matchingpath = LABEL(); } if (repeat_type == OP_EXACT) { count_match(common); OP2(SLJIT_SUB | SLJIT_SET_Z, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, rmax_label); } else if (repeat_type == OP_UPTO) { /* We need to preserve the counter. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); } if (bra == OP_BRAZERO) BACKTRACK_AS(bracket_backtrack)->zero_matchingpath = LABEL(); if (bra == OP_BRAMINZERO) { /* This is a backtrack path! (From the viewpoint of OP_BRAMINZERO) */ JUMPTO(SLJIT_JUMP, ((braminzero_backtrack *)parent)->matchingpath); if (braminzero != NULL) { JUMPHERE(braminzero); /* We need to release the end pointer to perform the backtrack for the zero-length iteration. When framesize is < 0, OP_ONCE will do the release itself. */ if (opcode == OP_ONCE && BACKTRACK_AS(bracket_backtrack)->u.framesize >= 0) { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); } else if (ket == OP_KETRMIN && opcode != OP_ONCE) free_stack(common, 1); } /* Continue to the normal backtrack. */ } if ((ket != OP_KET && bra != OP_BRAMINZERO) || bra == OP_BRAZERO) count_match(common); /* Skip the other alternatives. */ while (*cc == OP_ALT) cc += GET(cc, 1); cc += 1 + LINK_SIZE; if (opcode == OP_ONCE) { /* We temporarily encode the needs_control_head in the lowest bit. Note: on the target architectures of SLJIT the ((x << 1) >> 1) returns the same value for small signed numbers (including negative numbers). */ BACKTRACK_AS(bracket_backtrack)->u.framesize = ((unsigned int)BACKTRACK_AS(bracket_backtrack)->u.framesize << 1) | (needs_control_head ? 1 : 0); } return cc + repeat_length; } static pcre_uchar *compile_bracketpos_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; pcre_uchar opcode; int private_data_ptr; int cbraprivptr = 0; BOOL needs_control_head; int framesize; int stacksize; int offset = 0; BOOL zero = FALSE; pcre_uchar *ccbegin = NULL; int stack; /* Also contains the offset of control head. */ struct sljit_label *loop = NULL; struct jump_list *emptymatch = NULL; PUSH_BACKTRACK(sizeof(bracketpos_backtrack), cc, NULL); if (*cc == OP_BRAPOSZERO) { zero = TRUE; cc++; } opcode = *cc; private_data_ptr = PRIVATE_DATA(cc); SLJIT_ASSERT(private_data_ptr != 0); BACKTRACK_AS(bracketpos_backtrack)->private_data_ptr = private_data_ptr; switch(opcode) { case OP_BRAPOS: case OP_SBRAPOS: ccbegin = cc + 1 + LINK_SIZE; break; case OP_CBRAPOS: case OP_SCBRAPOS: offset = GET2(cc, 1 + LINK_SIZE); /* This case cannot be optimized in the same was as normal capturing brackets. */ SLJIT_ASSERT(common->optimized_cbracket[offset] == 0); cbraprivptr = OVECTOR_PRIV(offset); offset <<= 1; ccbegin = cc + 1 + LINK_SIZE + IMM2_SIZE; break; default: SLJIT_UNREACHABLE(); break; } framesize = get_framesize(common, cc, NULL, FALSE, &needs_control_head); BACKTRACK_AS(bracketpos_backtrack)->framesize = framesize; if (framesize < 0) { if (offset != 0) { stacksize = 2; if (common->capture_last_ptr != 0) stacksize++; } else stacksize = 1; if (needs_control_head) stacksize++; if (!zero) stacksize++; BACKTRACK_AS(bracketpos_backtrack)->stacksize = stacksize; allocate_stack(common, stacksize); if (framesize == no_frame) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); stack = 0; if (offset != 0) { stack = 2; OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); if (common->capture_last_ptr != 0) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); if (needs_control_head) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); if (common->capture_last_ptr != 0) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP1, 0); stack = 3; } } else { if (needs_control_head) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); stack = 1; } if (needs_control_head) stack++; if (!zero) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), SLJIT_IMM, 1); if (needs_control_head) { stack--; OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP2, 0); } } else { stacksize = framesize + 1; if (!zero) stacksize++; if (needs_control_head) stacksize++; if (offset == 0) stacksize++; BACKTRACK_AS(bracketpos_backtrack)->stacksize = stacksize; allocate_stack(common, stacksize); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); if (needs_control_head) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); stack = 0; if (!zero) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 1); stack = 1; } if (needs_control_head) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP2, 0); stack++; } if (offset == 0) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), STR_PTR, 0); stack++; } OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP1, 0); init_frame(common, cc, NULL, stacksize - 1, stacksize - framesize, FALSE); stack -= 1 + (offset == 0); } if (offset != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); loop = LABEL(); while (*cc != OP_KETRPOS) { backtrack->top = NULL; backtrack->topbacktracks = NULL; cc += GET(cc, 1); compile_matchingpath(common, ccbegin, cc, backtrack); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return NULL; if (framesize < 0) { if (framesize == no_frame) OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); if (offset != 0) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); if (common->capture_last_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); } else { if (opcode == OP_SBRAPOS) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); } /* Even if the match is empty, we need to reset the control head. */ if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(stack)); if (opcode == OP_SBRAPOS || opcode == OP_SCBRAPOS) add_jump(compiler, &emptymatch, CMP(SLJIT_EQUAL, TMP1, 0, STR_PTR, 0)); if (!zero) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0); } else { if (offset != 0) { OP2(SLJIT_SUB, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, stacksize * sizeof(sljit_sw)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); if (common->capture_last_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); } else { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP2(SLJIT_SUB, STACK_TOP, 0, TMP2, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); if (opcode == OP_SBRAPOS) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), STACK(-framesize - 2)); OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), STACK(-framesize - 2), STR_PTR, 0); } /* Even if the match is empty, we need to reset the control head. */ if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(stack)); if (opcode == OP_SBRAPOS || opcode == OP_SCBRAPOS) add_jump(compiler, &emptymatch, CMP(SLJIT_EQUAL, TMP1, 0, STR_PTR, 0)); if (!zero) { if (framesize < 0) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0); else OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); } } JUMPTO(SLJIT_JUMP, loop); flush_stubs(common); compile_backtrackingpath(common, backtrack->top); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return NULL; set_jumps(backtrack->topbacktracks, LABEL()); if (framesize < 0) { if (offset != 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); else OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); } else { if (offset != 0) { /* Last alternative. */ if (*cc == OP_KETRPOS) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); } else { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(TMP2), STACK(-framesize - 2)); } } if (*cc == OP_KETRPOS) break; ccbegin = cc + 1 + LINK_SIZE; } /* We don't have to restore the control head in case of a failed match. */ backtrack->topbacktracks = NULL; if (!zero) { if (framesize < 0) add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0)); else /* TMP2 is set to [private_data_ptr] above. */ add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_NOT_EQUAL, SLJIT_MEM1(TMP2), STACK(-stacksize), SLJIT_IMM, 0)); } /* None of them matched. */ set_jumps(emptymatch, LABEL()); count_match(common); return cc + 1 + LINK_SIZE; } static SLJIT_INLINE pcre_uchar *get_iterator_parameters(compiler_common *common, pcre_uchar *cc, pcre_uchar *opcode, pcre_uchar *type, sljit_u32 *max, sljit_u32 *exact, pcre_uchar **end) { int class_len; *opcode = *cc; *exact = 0; if (*opcode >= OP_STAR && *opcode <= OP_POSUPTO) { cc++; *type = OP_CHAR; } else if (*opcode >= OP_STARI && *opcode <= OP_POSUPTOI) { cc++; *type = OP_CHARI; *opcode -= OP_STARI - OP_STAR; } else if (*opcode >= OP_NOTSTAR && *opcode <= OP_NOTPOSUPTO) { cc++; *type = OP_NOT; *opcode -= OP_NOTSTAR - OP_STAR; } else if (*opcode >= OP_NOTSTARI && *opcode <= OP_NOTPOSUPTOI) { cc++; *type = OP_NOTI; *opcode -= OP_NOTSTARI - OP_STAR; } else if (*opcode >= OP_TYPESTAR && *opcode <= OP_TYPEPOSUPTO) { cc++; *opcode -= OP_TYPESTAR - OP_STAR; *type = OP_END; } else { SLJIT_ASSERT(*opcode == OP_CLASS || *opcode == OP_NCLASS || *opcode == OP_XCLASS); *type = *opcode; cc++; class_len = (*type < OP_XCLASS) ? (int)(1 + (32 / sizeof(pcre_uchar))) : GET(cc, 0); *opcode = cc[class_len - 1]; if (*opcode >= OP_CRSTAR && *opcode <= OP_CRMINQUERY) { *opcode -= OP_CRSTAR - OP_STAR; *end = cc + class_len; if (*opcode == OP_PLUS || *opcode == OP_MINPLUS) { *exact = 1; *opcode -= OP_PLUS - OP_STAR; } } else if (*opcode >= OP_CRPOSSTAR && *opcode <= OP_CRPOSQUERY) { *opcode -= OP_CRPOSSTAR - OP_POSSTAR; *end = cc + class_len; if (*opcode == OP_POSPLUS) { *exact = 1; *opcode = OP_POSSTAR; } } else { SLJIT_ASSERT(*opcode == OP_CRRANGE || *opcode == OP_CRMINRANGE || *opcode == OP_CRPOSRANGE); *max = GET2(cc, (class_len + IMM2_SIZE)); *exact = GET2(cc, class_len); if (*max == 0) { if (*opcode == OP_CRPOSRANGE) *opcode = OP_POSSTAR; else *opcode -= OP_CRRANGE - OP_STAR; } else { *max -= *exact; if (*max == 0) *opcode = OP_EXACT; else if (*max == 1) { if (*opcode == OP_CRPOSRANGE) *opcode = OP_POSQUERY; else *opcode -= OP_CRRANGE - OP_QUERY; } else { if (*opcode == OP_CRPOSRANGE) *opcode = OP_POSUPTO; else *opcode -= OP_CRRANGE - OP_UPTO; } } *end = cc + class_len + 2 * IMM2_SIZE; } return cc; } switch(*opcode) { case OP_EXACT: *exact = GET2(cc, 0); cc += IMM2_SIZE; break; case OP_PLUS: case OP_MINPLUS: *exact = 1; *opcode -= OP_PLUS - OP_STAR; break; case OP_POSPLUS: *exact = 1; *opcode = OP_POSSTAR; break; case OP_UPTO: case OP_MINUPTO: case OP_POSUPTO: *max = GET2(cc, 0); cc += IMM2_SIZE; break; } if (*type == OP_END) { *type = *cc; *end = next_opcode(common, cc); cc++; return cc; } *end = cc + 1; #ifdef SUPPORT_UTF if (common->utf && HAS_EXTRALEN(*cc)) *end += GET_EXTRALEN(*cc); #endif return cc; } static pcre_uchar *compile_iterator_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; pcre_uchar opcode; pcre_uchar type; sljit_u32 max = 0, exact; BOOL fast_fail; sljit_s32 fast_str_ptr; BOOL charpos_enabled; pcre_uchar charpos_char; unsigned int charpos_othercasebit; pcre_uchar *end; jump_list *no_match = NULL; jump_list *no_char1_match = NULL; struct sljit_jump *jump = NULL; struct sljit_label *label; int private_data_ptr = PRIVATE_DATA(cc); int base = (private_data_ptr == 0) ? SLJIT_MEM1(STACK_TOP) : SLJIT_MEM1(SLJIT_SP); int offset0 = (private_data_ptr == 0) ? STACK(0) : private_data_ptr; int offset1 = (private_data_ptr == 0) ? STACK(1) : private_data_ptr + (int)sizeof(sljit_sw); int tmp_base, tmp_offset; PUSH_BACKTRACK(sizeof(char_iterator_backtrack), cc, NULL); fast_str_ptr = PRIVATE_DATA(cc + 1); fast_fail = TRUE; SLJIT_ASSERT(common->fast_forward_bc_ptr == NULL || fast_str_ptr == 0 || cc == common->fast_forward_bc_ptr); if (cc == common->fast_forward_bc_ptr) fast_fail = FALSE; else if (common->fast_fail_start_ptr == 0) fast_str_ptr = 0; SLJIT_ASSERT(common->fast_forward_bc_ptr != NULL || fast_str_ptr == 0 || (fast_str_ptr >= common->fast_fail_start_ptr && fast_str_ptr <= common->fast_fail_end_ptr)); cc = get_iterator_parameters(common, cc, &opcode, &type, &max, &exact, &end); if (type != OP_EXTUNI) { tmp_base = TMP3; tmp_offset = 0; } else { tmp_base = SLJIT_MEM1(SLJIT_SP); tmp_offset = POSSESSIVE0; } if (fast_fail && fast_str_ptr != 0) add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), fast_str_ptr)); /* Handle fixed part first. */ if (exact > 1) { SLJIT_ASSERT(fast_str_ptr == 0); if (common->mode == JIT_COMPILE #ifdef SUPPORT_UTF && !common->utf #endif && type != OP_ANYNL && type != OP_EXTUNI) { OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(exact)); add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_GREATER, TMP1, 0, STR_END, 0)); OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, exact); label = LABEL(); compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks, FALSE); OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); } else { OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, exact); label = LABEL(); compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks, TRUE); OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); } } else if (exact == 1) compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks, TRUE); switch(opcode) { case OP_STAR: case OP_UPTO: SLJIT_ASSERT(fast_str_ptr == 0 || opcode == OP_STAR); if (type == OP_ANYNL || type == OP_EXTUNI) { SLJIT_ASSERT(private_data_ptr == 0); SLJIT_ASSERT(fast_str_ptr == 0); allocate_stack(common, 2); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); if (opcode == OP_UPTO) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, SLJIT_IMM, max); label = LABEL(); compile_char1_matchingpath(common, type, cc, &BACKTRACK_AS(char_iterator_backtrack)->u.backtracks, TRUE); if (opcode == OP_UPTO) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); jump = JUMP(SLJIT_ZERO); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, TMP1, 0); } /* We cannot use TMP3 because of this allocate_stack. */ allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); JUMPTO(SLJIT_JUMP, label); if (jump != NULL) JUMPHERE(jump); } else { charpos_enabled = FALSE; charpos_char = 0; charpos_othercasebit = 0; if ((type != OP_CHAR && type != OP_CHARI) && (*end == OP_CHAR || *end == OP_CHARI)) { charpos_enabled = TRUE; #ifdef SUPPORT_UTF charpos_enabled = !common->utf || !HAS_EXTRALEN(end[1]); #endif if (charpos_enabled && *end == OP_CHARI && char_has_othercase(common, end + 1)) { charpos_othercasebit = char_get_othercase_bit(common, end + 1); if (charpos_othercasebit == 0) charpos_enabled = FALSE; } if (charpos_enabled) { charpos_char = end[1]; /* Consumpe the OP_CHAR opcode. */ end += 2; #if defined COMPILE_PCRE8 SLJIT_ASSERT((charpos_othercasebit >> 8) == 0); #elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 SLJIT_ASSERT((charpos_othercasebit >> 9) == 0); if ((charpos_othercasebit & 0x100) != 0) charpos_othercasebit = (charpos_othercasebit & 0xff) << 8; #endif if (charpos_othercasebit != 0) charpos_char |= charpos_othercasebit; BACKTRACK_AS(char_iterator_backtrack)->u.charpos.enabled = TRUE; BACKTRACK_AS(char_iterator_backtrack)->u.charpos.chr = charpos_char; BACKTRACK_AS(char_iterator_backtrack)->u.charpos.othercasebit = charpos_othercasebit; } } if (charpos_enabled) { if (opcode == OP_UPTO) OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max + 1); /* Search the first instance of charpos_char. */ jump = JUMP(SLJIT_JUMP); label = LABEL(); if (opcode == OP_UPTO) { OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_ZERO)); } compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks, FALSE); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); JUMPHERE(jump); detect_partial_match(common, &backtrack->topbacktracks); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); if (charpos_othercasebit != 0) OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, charpos_othercasebit); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, charpos_char, label); if (private_data_ptr == 0) allocate_stack(common, 2); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); OP1(SLJIT_MOV, base, offset1, STR_PTR, 0); if (opcode == OP_UPTO) { OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); add_jump(compiler, &no_match, JUMP(SLJIT_ZERO)); } /* Search the last instance of charpos_char. */ label = LABEL(); compile_char1_matchingpath(common, type, cc, &no_match, FALSE); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); detect_partial_match(common, &no_match); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); if (charpos_othercasebit != 0) OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, charpos_othercasebit); if (opcode == OP_STAR) { CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, charpos_char, label); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); } else { jump = CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, charpos_char); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); JUMPHERE(jump); } if (opcode == OP_UPTO) { OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); } else JUMPTO(SLJIT_JUMP, label); set_jumps(no_match, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); } #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 else if (common->utf) { if (private_data_ptr == 0) allocate_stack(common, 2); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); OP1(SLJIT_MOV, base, offset1, STR_PTR, 0); if (opcode == OP_UPTO) OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max); label = LABEL(); compile_char1_matchingpath(common, type, cc, &no_match, TRUE); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); if (opcode == OP_UPTO) { OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); } else JUMPTO(SLJIT_JUMP, label); set_jumps(no_match, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); } #endif else { if (private_data_ptr == 0) allocate_stack(common, 2); OP1(SLJIT_MOV, base, offset1, STR_PTR, 0); if (opcode == OP_UPTO) OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max); label = LABEL(); detect_partial_match(common, &no_match); compile_char1_matchingpath(common, type, cc, &no_char1_match, FALSE); if (opcode == OP_UPTO) { OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); } else JUMPTO(SLJIT_JUMP, label); set_jumps(no_char1_match, LABEL()); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); set_jumps(no_match, LABEL()); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); } } BACKTRACK_AS(char_iterator_backtrack)->matchingpath = LABEL(); break; case OP_MINSTAR: if (private_data_ptr == 0) allocate_stack(common, 1); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); BACKTRACK_AS(char_iterator_backtrack)->matchingpath = LABEL(); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); break; case OP_MINUPTO: SLJIT_ASSERT(fast_str_ptr == 0); if (private_data_ptr == 0) allocate_stack(common, 2); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); OP1(SLJIT_MOV, base, offset1, SLJIT_IMM, max + 1); BACKTRACK_AS(char_iterator_backtrack)->matchingpath = LABEL(); break; case OP_QUERY: case OP_MINQUERY: SLJIT_ASSERT(fast_str_ptr == 0); if (private_data_ptr == 0) allocate_stack(common, 1); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); if (opcode == OP_QUERY) compile_char1_matchingpath(common, type, cc, &BACKTRACK_AS(char_iterator_backtrack)->u.backtracks, TRUE); BACKTRACK_AS(char_iterator_backtrack)->matchingpath = LABEL(); break; case OP_EXACT: break; case OP_POSSTAR: #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf) { OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); label = LABEL(); compile_char1_matchingpath(common, type, cc, &no_match, TRUE); OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); JUMPTO(SLJIT_JUMP, label); set_jumps(no_match, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); break; } #endif label = LABEL(); detect_partial_match(common, &no_match); compile_char1_matchingpath(common, type, cc, &no_char1_match, FALSE); JUMPTO(SLJIT_JUMP, label); set_jumps(no_char1_match, LABEL()); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); set_jumps(no_match, LABEL()); if (fast_str_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), fast_str_ptr, STR_PTR, 0); break; case OP_POSUPTO: SLJIT_ASSERT(fast_str_ptr == 0); #if defined SUPPORT_UTF && !defined COMPILE_PCRE32 if (common->utf) { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, STR_PTR, 0); OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max); label = LABEL(); compile_char1_matchingpath(common, type, cc, &no_match, TRUE); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, STR_PTR, 0); OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); set_jumps(no_match, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1); break; } #endif OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max); label = LABEL(); detect_partial_match(common, &no_match); compile_char1_matchingpath(common, type, cc, &no_char1_match, FALSE); OP2(SLJIT_SUB | SLJIT_SET_Z, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); JUMPTO(SLJIT_NOT_ZERO, label); OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); set_jumps(no_char1_match, LABEL()); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); set_jumps(no_match, LABEL()); break; case OP_POSQUERY: SLJIT_ASSERT(fast_str_ptr == 0); OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); compile_char1_matchingpath(common, type, cc, &no_match, TRUE); OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); set_jumps(no_match, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); break; default: SLJIT_UNREACHABLE(); break; } count_match(common); return end; } static SLJIT_INLINE pcre_uchar *compile_fail_accept_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); if (*cc == OP_FAIL) { add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); return cc + 1; } if (*cc == OP_ASSERT_ACCEPT || common->currententry != NULL || !common->might_be_empty) { /* No need to check notempty conditions. */ if (common->accept_label == NULL) add_jump(compiler, &common->accept, JUMP(SLJIT_JUMP)); else JUMPTO(SLJIT_JUMP, common->accept_label); return cc + 1; } if (common->accept_label == NULL) add_jump(compiler, &common->accept, CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0))); else CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), common->accept_label); OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty)); add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty_atstart)); if (common->accept_label == NULL) add_jump(compiler, &common->accept, CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); else CMPTO(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, 0, common->accept_label); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); if (common->accept_label == NULL) add_jump(compiler, &common->accept, CMP(SLJIT_NOT_EQUAL, TMP2, 0, STR_PTR, 0)); else CMPTO(SLJIT_NOT_EQUAL, TMP2, 0, STR_PTR, 0, common->accept_label); add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); return cc + 1; } static SLJIT_INLINE pcre_uchar *compile_close_matchingpath(compiler_common *common, pcre_uchar *cc) { DEFINE_COMPILER; int offset = GET2(cc, 1); BOOL optimized_cbracket = common->optimized_cbracket[offset] != 0; /* Data will be discarded anyway... */ if (common->currententry != NULL) return cc + 1 + IMM2_SIZE; if (!optimized_cbracket) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR_PRIV(offset)); offset <<= 1; OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); if (!optimized_cbracket) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); return cc + 1 + IMM2_SIZE; } static SLJIT_INLINE pcre_uchar *compile_control_verb_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; pcre_uchar opcode = *cc; pcre_uchar *ccend = cc + 1; if (opcode == OP_PRUNE_ARG || opcode == OP_SKIP_ARG || opcode == OP_THEN_ARG) ccend += 2 + cc[1]; PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); if (opcode == OP_SKIP) { allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); return ccend; } if (opcode == OP_PRUNE_ARG || opcode == OP_THEN_ARG) { OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)(cc + 2)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr), TMP2, 0); } return ccend; } static pcre_uchar then_trap_opcode[1] = { OP_THEN_TRAP }; static SLJIT_INLINE void compile_then_trap_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; BOOL needs_control_head; int size; PUSH_BACKTRACK_NOVALUE(sizeof(then_trap_backtrack), cc); common->then_trap = BACKTRACK_AS(then_trap_backtrack); BACKTRACK_AS(then_trap_backtrack)->common.cc = then_trap_opcode; BACKTRACK_AS(then_trap_backtrack)->start = (sljit_sw)(cc - common->start); BACKTRACK_AS(then_trap_backtrack)->framesize = get_framesize(common, cc, ccend, FALSE, &needs_control_head); size = BACKTRACK_AS(then_trap_backtrack)->framesize; size = 3 + (size < 0 ? 0 : size); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); allocate_stack(common, size); if (size > 3) OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0, SLJIT_IMM, (size - 3) * sizeof(sljit_sw)); else OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 1), SLJIT_IMM, BACKTRACK_AS(then_trap_backtrack)->start); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 2), SLJIT_IMM, type_then_trap); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 3), TMP2, 0); size = BACKTRACK_AS(then_trap_backtrack)->framesize; if (size >= 0) init_frame(common, cc, ccend, size - 1, 0, FALSE); } static void compile_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, backtrack_common *parent) { DEFINE_COMPILER; backtrack_common *backtrack; BOOL has_then_trap = FALSE; then_trap_backtrack *save_then_trap = NULL; SLJIT_ASSERT(*ccend == OP_END || (*ccend >= OP_ALT && *ccend <= OP_KETRPOS)); if (common->has_then && common->then_offsets[cc - common->start] != 0) { SLJIT_ASSERT(*ccend != OP_END && common->control_head_ptr != 0); has_then_trap = TRUE; save_then_trap = common->then_trap; /* Tail item on backtrack. */ compile_then_trap_matchingpath(common, cc, ccend, parent); } while (cc < ccend) { switch(*cc) { case OP_SOD: case OP_SOM: case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: case OP_EODN: case OP_EOD: case OP_DOLL: case OP_DOLLM: case OP_CIRC: case OP_CIRCM: case OP_REVERSE: cc = compile_simple_assertion_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); break; case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: case OP_ALLANY: case OP_ANYBYTE: case OP_NOTPROP: case OP_PROP: case OP_ANYNL: case OP_NOT_HSPACE: case OP_HSPACE: case OP_NOT_VSPACE: case OP_VSPACE: case OP_EXTUNI: case OP_NOT: case OP_NOTI: cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE); break; case OP_SET_SOM: PUSH_BACKTRACK_NOVALUE(sizeof(backtrack_common), cc); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); cc++; break; case OP_CHAR: case OP_CHARI: if (common->mode == JIT_COMPILE) cc = compile_charn_matchingpath(common, cc, ccend, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); else cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE); break; case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_UPTOI: case OP_MINUPTOI: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: case OP_TYPEPOSUPTO: cc = compile_iterator_matchingpath(common, cc, parent); break; case OP_CLASS: case OP_NCLASS: if (cc[1 + (32 / sizeof(pcre_uchar))] >= OP_CRSTAR && cc[1 + (32 / sizeof(pcre_uchar))] <= OP_CRPOSRANGE) cc = compile_iterator_matchingpath(common, cc, parent); else cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE); break; #if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 case OP_XCLASS: if (*(cc + GET(cc, 1)) >= OP_CRSTAR && *(cc + GET(cc, 1)) <= OP_CRPOSRANGE) cc = compile_iterator_matchingpath(common, cc, parent); else cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE); break; #endif case OP_REF: case OP_REFI: if (cc[1 + IMM2_SIZE] >= OP_CRSTAR && cc[1 + IMM2_SIZE] <= OP_CRPOSRANGE) cc = compile_ref_iterator_matchingpath(common, cc, parent); else { compile_ref_matchingpath(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE, FALSE); cc += 1 + IMM2_SIZE; } break; case OP_DNREF: case OP_DNREFI: if (cc[1 + 2 * IMM2_SIZE] >= OP_CRSTAR && cc[1 + 2 * IMM2_SIZE] <= OP_CRPOSRANGE) cc = compile_ref_iterator_matchingpath(common, cc, parent); else { compile_dnref_search(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); compile_ref_matchingpath(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE, FALSE); cc += 1 + 2 * IMM2_SIZE; } break; case OP_RECURSE: cc = compile_recurse_matchingpath(common, cc, parent); break; case OP_CALLOUT: cc = compile_callout_matchingpath(common, cc, parent); break; case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: PUSH_BACKTRACK_NOVALUE(sizeof(assert_backtrack), cc); cc = compile_assert_matchingpath(common, cc, BACKTRACK_AS(assert_backtrack), FALSE); break; case OP_BRAMINZERO: PUSH_BACKTRACK_NOVALUE(sizeof(braminzero_backtrack), cc); cc = bracketend(cc + 1); if (*(cc - 1 - LINK_SIZE) != OP_KETRMIN) { allocate_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); } else { allocate_stack(common, 2); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), STR_PTR, 0); } BACKTRACK_AS(braminzero_backtrack)->matchingpath = LABEL(); count_match(common); break; case OP_ONCE: case OP_ONCE_NC: case OP_BRA: case OP_CBRA: case OP_COND: case OP_SBRA: case OP_SCBRA: case OP_SCOND: cc = compile_bracket_matchingpath(common, cc, parent); break; case OP_BRAZERO: if (cc[1] > OP_ASSERTBACK_NOT) cc = compile_bracket_matchingpath(common, cc, parent); else { PUSH_BACKTRACK_NOVALUE(sizeof(assert_backtrack), cc); cc = compile_assert_matchingpath(common, cc, BACKTRACK_AS(assert_backtrack), FALSE); } break; case OP_BRAPOS: case OP_CBRAPOS: case OP_SBRAPOS: case OP_SCBRAPOS: case OP_BRAPOSZERO: cc = compile_bracketpos_matchingpath(common, cc, parent); break; case OP_MARK: PUSH_BACKTRACK_NOVALUE(sizeof(backtrack_common), cc); SLJIT_ASSERT(common->mark_ptr != 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); allocate_stack(common, common->has_skip_arg ? 5 : 1); OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0), TMP2, 0); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)(cc + 2)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr), TMP2, 0); if (common->has_skip_arg) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, type_mark); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), SLJIT_IMM, (sljit_sw)(cc + 2)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(3), STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); } cc += 1 + 2 + cc[1]; break; case OP_PRUNE: case OP_PRUNE_ARG: case OP_SKIP: case OP_SKIP_ARG: case OP_THEN: case OP_THEN_ARG: case OP_COMMIT: cc = compile_control_verb_matchingpath(common, cc, parent); break; case OP_FAIL: case OP_ACCEPT: case OP_ASSERT_ACCEPT: cc = compile_fail_accept_matchingpath(common, cc, parent); break; case OP_CLOSE: cc = compile_close_matchingpath(common, cc); break; case OP_SKIPZERO: cc = bracketend(cc + 1); break; default: SLJIT_UNREACHABLE(); return; } if (cc == NULL) return; } if (has_then_trap) { /* Head item on backtrack. */ PUSH_BACKTRACK_NOVALUE(sizeof(then_trap_backtrack), cc); BACKTRACK_AS(then_trap_backtrack)->common.cc = then_trap_opcode; BACKTRACK_AS(then_trap_backtrack)->then_trap = common->then_trap; common->then_trap = save_then_trap; } SLJIT_ASSERT(cc == ccend); } #undef PUSH_BACKTRACK #undef PUSH_BACKTRACK_NOVALUE #undef BACKTRACK_AS #define COMPILE_BACKTRACKINGPATH(current) \ do \ { \ compile_backtrackingpath(common, (current)); \ if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ return; \ } \ while (0) #define CURRENT_AS(type) ((type *)current) static void compile_iterator_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; pcre_uchar *cc = current->cc; pcre_uchar opcode; pcre_uchar type; sljit_u32 max = 0, exact; struct sljit_label *label = NULL; struct sljit_jump *jump = NULL; jump_list *jumplist = NULL; pcre_uchar *end; int private_data_ptr = PRIVATE_DATA(cc); int base = (private_data_ptr == 0) ? SLJIT_MEM1(STACK_TOP) : SLJIT_MEM1(SLJIT_SP); int offset0 = (private_data_ptr == 0) ? STACK(0) : private_data_ptr; int offset1 = (private_data_ptr == 0) ? STACK(1) : private_data_ptr + (int)sizeof(sljit_sw); cc = get_iterator_parameters(common, cc, &opcode, &type, &max, &exact, &end); switch(opcode) { case OP_STAR: case OP_UPTO: if (type == OP_ANYNL || type == OP_EXTUNI) { SLJIT_ASSERT(private_data_ptr == 0); set_jumps(CURRENT_AS(char_iterator_backtrack)->u.backtracks, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(char_iterator_backtrack)->matchingpath); } else { if (CURRENT_AS(char_iterator_backtrack)->u.charpos.enabled) { OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); OP1(SLJIT_MOV, TMP2, 0, base, offset1); OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); jump = CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, TMP2, 0); label = LABEL(); OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); if (CURRENT_AS(char_iterator_backtrack)->u.charpos.othercasebit != 0) OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, CURRENT_AS(char_iterator_backtrack)->u.charpos.othercasebit); CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, CURRENT_AS(char_iterator_backtrack)->u.charpos.chr, CURRENT_AS(char_iterator_backtrack)->matchingpath); skip_char_back(common); CMPTO(SLJIT_GREATER, STR_PTR, 0, TMP2, 0, label); } else { OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); jump = CMP(SLJIT_LESS_EQUAL, STR_PTR, 0, base, offset1); skip_char_back(common); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); JUMPTO(SLJIT_JUMP, CURRENT_AS(char_iterator_backtrack)->matchingpath); } JUMPHERE(jump); if (private_data_ptr == 0) free_stack(common, 2); } break; case OP_MINSTAR: OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); compile_char1_matchingpath(common, type, cc, &jumplist, TRUE); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); JUMPTO(SLJIT_JUMP, CURRENT_AS(char_iterator_backtrack)->matchingpath); set_jumps(jumplist, LABEL()); if (private_data_ptr == 0) free_stack(common, 1); break; case OP_MINUPTO: OP1(SLJIT_MOV, TMP1, 0, base, offset1); OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); OP2(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); add_jump(compiler, &jumplist, JUMP(SLJIT_ZERO)); OP1(SLJIT_MOV, base, offset1, TMP1, 0); compile_char1_matchingpath(common, type, cc, &jumplist, TRUE); OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); JUMPTO(SLJIT_JUMP, CURRENT_AS(char_iterator_backtrack)->matchingpath); set_jumps(jumplist, LABEL()); if (private_data_ptr == 0) free_stack(common, 2); break; case OP_QUERY: OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(char_iterator_backtrack)->matchingpath); jump = JUMP(SLJIT_JUMP); set_jumps(CURRENT_AS(char_iterator_backtrack)->u.backtracks, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); JUMPTO(SLJIT_JUMP, CURRENT_AS(char_iterator_backtrack)->matchingpath); JUMPHERE(jump); if (private_data_ptr == 0) free_stack(common, 1); break; case OP_MINQUERY: OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); jump = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); compile_char1_matchingpath(common, type, cc, &jumplist, TRUE); JUMPTO(SLJIT_JUMP, CURRENT_AS(char_iterator_backtrack)->matchingpath); set_jumps(jumplist, LABEL()); JUMPHERE(jump); if (private_data_ptr == 0) free_stack(common, 1); break; case OP_EXACT: case OP_POSSTAR: case OP_POSQUERY: case OP_POSUPTO: break; default: SLJIT_UNREACHABLE(); break; } set_jumps(current->topbacktracks, LABEL()); } static SLJIT_INLINE void compile_ref_iterator_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; pcre_uchar *cc = current->cc; BOOL ref = (*cc == OP_REF || *cc == OP_REFI); pcre_uchar type; type = cc[ref ? 1 + IMM2_SIZE : 1 + 2 * IMM2_SIZE]; if ((type & 0x1) == 0) { /* Maximize case. */ set_jumps(current->topbacktracks, LABEL()); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(ref_iterator_backtrack)->matchingpath); return; } OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(ref_iterator_backtrack)->matchingpath); set_jumps(current->topbacktracks, LABEL()); free_stack(common, ref ? 2 : 3); } static SLJIT_INLINE void compile_recurse_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; if (CURRENT_AS(recurse_backtrack)->inlined_pattern) compile_backtrackingpath(common, current->top); set_jumps(current->topbacktracks, LABEL()); if (CURRENT_AS(recurse_backtrack)->inlined_pattern) return; if (common->has_set_som && common->mark_ptr != 0) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); free_stack(common, 2); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0); } else if (common->has_set_som || common->mark_ptr != 0) { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->has_set_som ? (int)(OVECTOR(0)) : common->mark_ptr, TMP2, 0); } } static void compile_assert_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; pcre_uchar *cc = current->cc; pcre_uchar bra = OP_BRA; struct sljit_jump *brajump = NULL; SLJIT_ASSERT(*cc != OP_BRAMINZERO); if (*cc == OP_BRAZERO) { bra = *cc; cc++; } if (bra == OP_BRAZERO) { SLJIT_ASSERT(current->topbacktracks == NULL); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); } if (CURRENT_AS(assert_backtrack)->framesize < 0) { set_jumps(current->topbacktracks, LABEL()); if (bra == OP_BRAZERO) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(assert_backtrack)->matchingpath); free_stack(common, 1); } return; } if (bra == OP_BRAZERO) { if (*cc == OP_ASSERT_NOT || *cc == OP_ASSERTBACK_NOT) { OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(assert_backtrack)->matchingpath); free_stack(common, 1); return; } free_stack(common, 1); brajump = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); } if (*cc == OP_ASSERT || *cc == OP_ASSERTBACK) { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(assert_backtrack)->private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(assert_backtrack)->private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-CURRENT_AS(assert_backtrack)->framesize - 1)); set_jumps(current->topbacktracks, LABEL()); } else set_jumps(current->topbacktracks, LABEL()); if (bra == OP_BRAZERO) { /* We know there is enough place on the stack. */ OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); JUMPTO(SLJIT_JUMP, CURRENT_AS(assert_backtrack)->matchingpath); JUMPHERE(brajump); } } static void compile_bracket_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; int opcode, stacksize, alt_count, alt_max; int offset = 0; int private_data_ptr = CURRENT_AS(bracket_backtrack)->private_data_ptr; int repeat_ptr = 0, repeat_type = 0, repeat_count = 0; pcre_uchar *cc = current->cc; pcre_uchar *ccbegin; pcre_uchar *ccprev; pcre_uchar bra = OP_BRA; pcre_uchar ket; assert_backtrack *assert; sljit_uw *next_update_addr = NULL; BOOL has_alternatives; BOOL needs_control_head = FALSE; struct sljit_jump *brazero = NULL; struct sljit_jump *alt1 = NULL; struct sljit_jump *alt2 = NULL; struct sljit_jump *once = NULL; struct sljit_jump *cond = NULL; struct sljit_label *rmin_label = NULL; struct sljit_label *exact_label = NULL; if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) { bra = *cc; cc++; } opcode = *cc; ccbegin = bracketend(cc) - 1 - LINK_SIZE; ket = *ccbegin; if (ket == OP_KET && PRIVATE_DATA(ccbegin) != 0) { repeat_ptr = PRIVATE_DATA(ccbegin); repeat_type = PRIVATE_DATA(ccbegin + 2); repeat_count = PRIVATE_DATA(ccbegin + 3); SLJIT_ASSERT(repeat_type != 0 && repeat_count != 0); if (repeat_type == OP_UPTO) ket = OP_KETRMAX; if (repeat_type == OP_MINUPTO) ket = OP_KETRMIN; } ccbegin = cc; cc += GET(cc, 1); has_alternatives = *cc == OP_ALT; if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) has_alternatives = (ccbegin[1 + LINK_SIZE] >= OP_ASSERT && ccbegin[1 + LINK_SIZE] <= OP_ASSERTBACK_NOT) || CURRENT_AS(bracket_backtrack)->u.condfailed != NULL; if (opcode == OP_CBRA || opcode == OP_SCBRA) offset = (GET2(ccbegin, 1 + LINK_SIZE)) << 1; if (SLJIT_UNLIKELY(opcode == OP_COND) && (*cc == OP_KETRMAX || *cc == OP_KETRMIN)) opcode = OP_SCOND; if (SLJIT_UNLIKELY(opcode == OP_ONCE_NC)) opcode = OP_ONCE; alt_max = has_alternatives ? no_alternatives(ccbegin) : 0; /* Decoding the needs_control_head in framesize. */ if (opcode == OP_ONCE) { needs_control_head = (CURRENT_AS(bracket_backtrack)->u.framesize & 0x1) != 0; CURRENT_AS(bracket_backtrack)->u.framesize >>= 1; } if (ket != OP_KET && repeat_type != 0) { /* TMP1 is used in OP_KETRMIN below. */ OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); if (repeat_type == OP_UPTO) OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0, SLJIT_IMM, 1); else OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0); } if (ket == OP_KETRMAX) { if (bra == OP_BRAZERO) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); brazero = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0); } } else if (ket == OP_KETRMIN) { if (bra != OP_BRAMINZERO) { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); if (repeat_type != 0) { /* TMP1 was set a few lines above. */ CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); /* Drop STR_PTR for non-greedy plus quantifier. */ if (opcode != OP_ONCE) free_stack(common, 1); } else if (opcode >= OP_SBRA || opcode == OP_ONCE) { /* Checking zero-length iteration. */ if (opcode != OP_ONCE || CURRENT_AS(bracket_backtrack)->u.framesize < 0) CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); else { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(TMP1), STACK(-CURRENT_AS(bracket_backtrack)->u.framesize - 2), CURRENT_AS(bracket_backtrack)->recursive_matchingpath); } /* Drop STR_PTR for non-greedy plus quantifier. */ if (opcode != OP_ONCE) free_stack(common, 1); } else JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); } rmin_label = LABEL(); if (repeat_type != 0) OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); } else if (bra == OP_BRAZERO) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); brazero = CMP(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0); } else if (repeat_type == OP_EXACT) { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); exact_label = LABEL(); } if (offset != 0) { if (common->capture_last_ptr != 0) { SLJIT_ASSERT(common->optimized_cbracket[offset >> 1] == 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, TMP1, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); free_stack(common, 3); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP2, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP1, 0); } else if (common->optimized_cbracket[offset >> 1] == 0) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); free_stack(common, 2); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); } } if (SLJIT_UNLIKELY(opcode == OP_ONCE)) { if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); } once = JUMP(SLJIT_JUMP); } else if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) { if (has_alternatives) { /* Always exactly one alternative. */ OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); alt_max = 2; alt1 = CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, sizeof(sljit_uw)); } } else if (has_alternatives) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); if (alt_max > 4) { /* Table jump if alt_max is greater than 4. */ next_update_addr = allocate_read_only_data(common, alt_max * sizeof(sljit_uw)); if (SLJIT_UNLIKELY(next_update_addr == NULL)) return; sljit_emit_ijump(compiler, SLJIT_JUMP, SLJIT_MEM1(TMP1), (sljit_sw)next_update_addr); add_label_addr(common, next_update_addr++); } else { if (alt_max == 4) alt2 = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_uw)); alt1 = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, sizeof(sljit_uw)); } } COMPILE_BACKTRACKINGPATH(current->top); if (current->topbacktracks) set_jumps(current->topbacktracks, LABEL()); if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) { /* Conditional block always has at most one alternative. */ if (ccbegin[1 + LINK_SIZE] >= OP_ASSERT && ccbegin[1 + LINK_SIZE] <= OP_ASSERTBACK_NOT) { SLJIT_ASSERT(has_alternatives); assert = CURRENT_AS(bracket_backtrack)->u.assert; if (assert->framesize >= 0 && (ccbegin[1 + LINK_SIZE] == OP_ASSERT || ccbegin[1 + LINK_SIZE] == OP_ASSERTBACK)) { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-assert->framesize - 1)); } cond = JUMP(SLJIT_JUMP); set_jumps(CURRENT_AS(bracket_backtrack)->u.assert->condfailed, LABEL()); } else if (CURRENT_AS(bracket_backtrack)->u.condfailed != NULL) { SLJIT_ASSERT(has_alternatives); cond = JUMP(SLJIT_JUMP); set_jumps(CURRENT_AS(bracket_backtrack)->u.condfailed, LABEL()); } else SLJIT_ASSERT(!has_alternatives); } if (has_alternatives) { alt_count = sizeof(sljit_uw); do { current->top = NULL; current->topbacktracks = NULL; current->nextbacktracks = NULL; /* Conditional blocks always have an additional alternative, even if it is empty. */ if (*cc == OP_ALT) { ccprev = cc + 1 + LINK_SIZE; cc += GET(cc, 1); if (opcode != OP_COND && opcode != OP_SCOND) { if (opcode != OP_ONCE) { if (private_data_ptr != 0) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); else OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); } else OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(needs_control_head ? 1 : 0)); } compile_matchingpath(common, ccprev, cc, current); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return; } /* Instructions after the current alternative is successfully matched. */ /* There is a similar code in compile_bracket_matchingpath. */ if (opcode == OP_ONCE) match_once_common(common, ket, CURRENT_AS(bracket_backtrack)->u.framesize, private_data_ptr, has_alternatives, needs_control_head); stacksize = 0; if (repeat_type == OP_MINUPTO) { /* We need to preserve the counter. TMP2 will be used below. */ OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); stacksize++; } if (ket != OP_KET || bra != OP_BRA) stacksize++; if (offset != 0) { if (common->capture_last_ptr != 0) stacksize++; if (common->optimized_cbracket[offset >> 1] == 0) stacksize += 2; } if (opcode != OP_ONCE) stacksize++; if (stacksize > 0) allocate_stack(common, stacksize); stacksize = 0; if (repeat_type == OP_MINUPTO) { /* TMP2 was set above. */ OP2(SLJIT_SUB, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP2, 0, SLJIT_IMM, 1); stacksize++; } if (ket != OP_KET || bra != OP_BRA) { if (ket != OP_KET) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); else OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); stacksize++; } if (offset != 0) stacksize = match_capture_common(common, stacksize, offset, private_data_ptr); if (opcode != OP_ONCE) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, alt_count); if (offset != 0 && ket == OP_KETRMAX && common->optimized_cbracket[offset >> 1] != 0) { /* If ket is not OP_KETRMAX, this code path is executed after the jump to alternative_matchingpath. */ SLJIT_ASSERT(private_data_ptr == OVECTOR(offset + 0)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); } JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->alternative_matchingpath); if (opcode != OP_ONCE) { if (alt_max > 4) add_label_addr(common, next_update_addr++); else { if (alt_count != 2 * sizeof(sljit_uw)) { JUMPHERE(alt1); if (alt_max == 3 && alt_count == sizeof(sljit_uw)) alt2 = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_uw)); } else { JUMPHERE(alt2); if (alt_max == 4) alt1 = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 3 * sizeof(sljit_uw)); } } alt_count += sizeof(sljit_uw); } COMPILE_BACKTRACKINGPATH(current->top); if (current->topbacktracks) set_jumps(current->topbacktracks, LABEL()); SLJIT_ASSERT(!current->nextbacktracks); } while (*cc == OP_ALT); if (cond != NULL) { SLJIT_ASSERT(opcode == OP_COND || opcode == OP_SCOND); assert = CURRENT_AS(bracket_backtrack)->u.assert; if ((ccbegin[1 + LINK_SIZE] == OP_ASSERT_NOT || ccbegin[1 + LINK_SIZE] == OP_ASSERTBACK_NOT) && assert->framesize >= 0) { OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-assert->framesize - 1)); } JUMPHERE(cond); } /* Free the STR_PTR. */ if (private_data_ptr == 0) free_stack(common, 1); } if (offset != 0) { /* Using both tmp register is better for instruction scheduling. */ if (common->optimized_cbracket[offset >> 1] != 0) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); free_stack(common, 2); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); } else { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); } } else if (opcode == OP_SBRA || opcode == OP_SCOND) { OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); } else if (opcode == OP_ONCE) { cc = ccbegin + GET(ccbegin, 1); stacksize = needs_control_head ? 1 : 0; if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) { /* Reset head and drop saved frame. */ stacksize += CURRENT_AS(bracket_backtrack)->u.framesize + ((ket != OP_KET || *cc == OP_ALT) ? 2 : 1); } else if (ket == OP_KETRMAX || (*cc == OP_ALT && ket != OP_KETRMIN)) { /* The STR_PTR must be released. */ stacksize++; } if (stacksize > 0) free_stack(common, stacksize); JUMPHERE(once); /* Restore previous private_data_ptr */ if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-CURRENT_AS(bracket_backtrack)->u.framesize - 1)); else if (ket == OP_KETRMIN) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); /* See the comment below. */ free_stack(common, 2); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); } } if (repeat_type == OP_EXACT) { OP2(SLJIT_ADD, TMP1, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0); CMPTO(SLJIT_LESS_EQUAL, TMP1, 0, SLJIT_IMM, repeat_count, exact_label); } else if (ket == OP_KETRMAX) { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); if (bra != OP_BRAZERO) free_stack(common, 1); CMPTO(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); if (bra == OP_BRAZERO) { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->zero_matchingpath); JUMPHERE(brazero); free_stack(common, 1); } } else if (ket == OP_KETRMIN) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); /* OP_ONCE removes everything in case of a backtrack, so we don't need to explicitly release the STR_PTR. The extra release would affect badly the free_stack(2) above. */ if (opcode != OP_ONCE) free_stack(common, 1); CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, rmin_label); if (opcode == OP_ONCE) free_stack(common, bra == OP_BRAMINZERO ? 2 : 1); else if (bra == OP_BRAMINZERO) free_stack(common, 1); } else if (bra == OP_BRAZERO) { OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->zero_matchingpath); JUMPHERE(brazero); } } static SLJIT_INLINE void compile_bracketpos_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; int offset; struct sljit_jump *jump; if (CURRENT_AS(bracketpos_backtrack)->framesize < 0) { if (*current->cc == OP_CBRAPOS || *current->cc == OP_SCBRAPOS) { offset = (GET2(current->cc, 1 + LINK_SIZE)) << 1; OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); if (common->capture_last_ptr != 0) OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); if (common->capture_last_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, TMP1, 0); } set_jumps(current->topbacktracks, LABEL()); free_stack(common, CURRENT_AS(bracketpos_backtrack)->stacksize); return; } OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(bracketpos_backtrack)->private_data_ptr); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); if (current->topbacktracks) { jump = JUMP(SLJIT_JUMP); set_jumps(current->topbacktracks, LABEL()); /* Drop the stack frame. */ free_stack(common, CURRENT_AS(bracketpos_backtrack)->stacksize); JUMPHERE(jump); } OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(bracketpos_backtrack)->private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(-CURRENT_AS(bracketpos_backtrack)->framesize - 1)); } static SLJIT_INLINE void compile_braminzero_backtrackingpath(compiler_common *common, struct backtrack_common *current) { assert_backtrack backtrack; current->top = NULL; current->topbacktracks = NULL; current->nextbacktracks = NULL; if (current->cc[1] > OP_ASSERTBACK_NOT) { /* Manual call of compile_bracket_matchingpath and compile_bracket_backtrackingpath. */ compile_bracket_matchingpath(common, current->cc, current); compile_bracket_backtrackingpath(common, current->top); } else { memset(&backtrack, 0, sizeof(backtrack)); backtrack.common.cc = current->cc; backtrack.matchingpath = CURRENT_AS(braminzero_backtrack)->matchingpath; /* Manual call of compile_assert_matchingpath. */ compile_assert_matchingpath(common, current->cc, &backtrack, FALSE); } SLJIT_ASSERT(!current->nextbacktracks && !current->topbacktracks); } static SLJIT_INLINE void compile_control_verb_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; pcre_uchar opcode = *current->cc; struct sljit_label *loop; struct sljit_jump *jump; if (opcode == OP_THEN || opcode == OP_THEN_ARG) { if (common->then_trap != NULL) { SLJIT_ASSERT(common->control_head_ptr != 0); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, type_then_trap); OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, common->then_trap->start); jump = JUMP(SLJIT_JUMP); loop = LABEL(); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); JUMPHERE(jump); CMPTO(SLJIT_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0, loop); CMPTO(SLJIT_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0, loop); add_jump(compiler, &common->then_trap->quit, JUMP(SLJIT_JUMP)); return; } else if (common->positive_assert) { add_jump(compiler, &common->positive_assert_quit, JUMP(SLJIT_JUMP)); return; } } if (common->local_exit) { if (common->quit_label == NULL) add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); else JUMPTO(SLJIT_JUMP, common->quit_label); return; } if (opcode == OP_SKIP_ARG) { SLJIT_ASSERT(common->control_head_ptr != 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, (sljit_sw)(current->cc + 2)); sljit_emit_icall(compiler, SLJIT_CALL, SLJIT_RET(SW) | SLJIT_ARG1(SW) | SLJIT_ARG2(SW), SLJIT_IMM, SLJIT_FUNC_OFFSET(do_search_mark)); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); add_jump(compiler, &common->reset_match, CMP(SLJIT_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0)); return; } if (opcode == OP_SKIP) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); else OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_IMM, 0); add_jump(compiler, &common->reset_match, JUMP(SLJIT_JUMP)); } static SLJIT_INLINE void compile_then_trap_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; struct sljit_jump *jump; int size; if (CURRENT_AS(then_trap_backtrack)->then_trap) { common->then_trap = CURRENT_AS(then_trap_backtrack)->then_trap; return; } size = CURRENT_AS(then_trap_backtrack)->framesize; size = 3 + (size < 0 ? 0 : size); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(size - 3)); free_stack(common, size); jump = JUMP(SLJIT_JUMP); set_jumps(CURRENT_AS(then_trap_backtrack)->quit, LABEL()); /* STACK_TOP is set by THEN. */ if (CURRENT_AS(then_trap_backtrack)->framesize >= 0) add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 3); JUMPHERE(jump); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP1, 0); } static void compile_backtrackingpath(compiler_common *common, struct backtrack_common *current) { DEFINE_COMPILER; then_trap_backtrack *save_then_trap = common->then_trap; while (current) { if (current->nextbacktracks != NULL) set_jumps(current->nextbacktracks, LABEL()); switch(*current->cc) { case OP_SET_SOM: OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP1, 0); break; case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: case OP_EXACT: case OP_POSSTAR: case OP_POSPLUS: case OP_POSQUERY: case OP_POSUPTO: case OP_STARI: case OP_MINSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_UPTOI: case OP_MINUPTOI: case OP_EXACTI: case OP_POSSTARI: case OP_POSPLUSI: case OP_POSQUERYI: case OP_POSUPTOI: case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTEXACT: case OP_NOTPOSSTAR: case OP_NOTPOSPLUS: case OP_NOTPOSQUERY: case OP_NOTPOSUPTO: case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTEXACTI: case OP_NOTPOSSTARI: case OP_NOTPOSPLUSI: case OP_NOTPOSQUERYI: case OP_NOTPOSUPTOI: case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEEXACT: case OP_TYPEPOSSTAR: case OP_TYPEPOSPLUS: case OP_TYPEPOSQUERY: case OP_TYPEPOSUPTO: case OP_CLASS: case OP_NCLASS: #if defined SUPPORT_UTF || !defined COMPILE_PCRE8 case OP_XCLASS: #endif compile_iterator_backtrackingpath(common, current); break; case OP_REF: case OP_REFI: case OP_DNREF: case OP_DNREFI: compile_ref_iterator_backtrackingpath(common, current); break; case OP_RECURSE: compile_recurse_backtrackingpath(common, current); break; case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: compile_assert_backtrackingpath(common, current); break; case OP_ONCE: case OP_ONCE_NC: case OP_BRA: case OP_CBRA: case OP_COND: case OP_SBRA: case OP_SCBRA: case OP_SCOND: compile_bracket_backtrackingpath(common, current); break; case OP_BRAZERO: if (current->cc[1] > OP_ASSERTBACK_NOT) compile_bracket_backtrackingpath(common, current); else compile_assert_backtrackingpath(common, current); break; case OP_BRAPOS: case OP_CBRAPOS: case OP_SBRAPOS: case OP_SCBRAPOS: case OP_BRAPOSZERO: compile_bracketpos_backtrackingpath(common, current); break; case OP_BRAMINZERO: compile_braminzero_backtrackingpath(common, current); break; case OP_MARK: OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0)); if (common->has_skip_arg) OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); free_stack(common, common->has_skip_arg ? 5 : 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0); if (common->has_skip_arg) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0); break; case OP_THEN: case OP_THEN_ARG: case OP_PRUNE: case OP_PRUNE_ARG: case OP_SKIP: case OP_SKIP_ARG: compile_control_verb_backtrackingpath(common, current); break; case OP_COMMIT: if (!common->local_exit) OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); if (common->quit_label == NULL) add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); else JUMPTO(SLJIT_JUMP, common->quit_label); break; case OP_CALLOUT: case OP_FAIL: case OP_ACCEPT: case OP_ASSERT_ACCEPT: set_jumps(current->topbacktracks, LABEL()); break; case OP_THEN_TRAP: /* A virtual opcode for then traps. */ compile_then_trap_backtrackingpath(common, current); break; default: SLJIT_UNREACHABLE(); break; } current = current->prev; } common->then_trap = save_then_trap; } static SLJIT_INLINE void compile_recurse(compiler_common *common) { DEFINE_COMPILER; pcre_uchar *cc = common->start + common->currententry->start; pcre_uchar *ccbegin = cc + 1 + LINK_SIZE + (*cc == OP_BRA ? 0 : IMM2_SIZE); pcre_uchar *ccend = bracketend(cc) - (1 + LINK_SIZE); BOOL needs_control_head; int framesize = get_framesize(common, cc, NULL, TRUE, &needs_control_head); int private_data_size = get_private_data_copy_length(common, ccbegin, ccend, needs_control_head); int alternativesize; BOOL needs_frame; backtrack_common altbacktrack; struct sljit_jump *jump; /* Recurse captures then. */ common->then_trap = NULL; SLJIT_ASSERT(*cc == OP_BRA || *cc == OP_CBRA || *cc == OP_CBRAPOS || *cc == OP_SCBRA || *cc == OP_SCBRAPOS); needs_frame = framesize >= 0; if (!needs_frame) framesize = 0; alternativesize = *(cc + GET(cc, 1)) == OP_ALT ? 1 : 0; SLJIT_ASSERT(common->currententry->entry == NULL && common->recursive_head_ptr != 0); common->currententry->entry = LABEL(); set_jumps(common->currententry->calls, common->currententry->entry); sljit_emit_fast_enter(compiler, TMP2, 0); count_match(common); allocate_stack(common, private_data_size + framesize + alternativesize); OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(private_data_size + framesize + alternativesize - 1), TMP2, 0); copy_private_data(common, ccbegin, ccend, TRUE, framesize + alternativesize, private_data_size + framesize + alternativesize, needs_control_head); if (needs_control_head) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, STACK_TOP, 0); if (needs_frame) init_frame(common, cc, NULL, framesize + alternativesize - 1, alternativesize, TRUE); if (alternativesize > 0) OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); memset(&altbacktrack, 0, sizeof(backtrack_common)); common->quit_label = NULL; common->accept_label = NULL; common->quit = NULL; common->accept = NULL; altbacktrack.cc = ccbegin; cc += GET(cc, 1); while (1) { altbacktrack.top = NULL; altbacktrack.topbacktracks = NULL; if (altbacktrack.cc != ccbegin) OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); compile_matchingpath(common, altbacktrack.cc, cc, &altbacktrack); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return; add_jump(compiler, &common->accept, JUMP(SLJIT_JUMP)); compile_backtrackingpath(common, altbacktrack.top); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) return; set_jumps(altbacktrack.topbacktracks, LABEL()); if (*cc != OP_ALT) break; altbacktrack.cc = cc + 1 + LINK_SIZE; cc += GET(cc, 1); } /* None of them matched. */ OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 0); jump = JUMP(SLJIT_JUMP); if (common->quit != NULL) { set_jumps(common->quit, LABEL()); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr); if (needs_frame) { OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); } OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 0); common->quit = NULL; add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); } set_jumps(common->accept, LABEL()); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr); if (needs_frame) { OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); } OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 1); JUMPHERE(jump); if (common->quit != NULL) set_jumps(common->quit, LABEL()); copy_private_data(common, ccbegin, ccend, FALSE, framesize + alternativesize, private_data_size + framesize + alternativesize, needs_control_head); free_stack(common, private_data_size + framesize + alternativesize); if (needs_control_head) { OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(-3)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(-2)); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, TMP1, 0); OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0); } else { OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(-2)); OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, TMP2, 0); } sljit_emit_fast_return(compiler, SLJIT_MEM1(STACK_TOP), STACK(-1)); } #undef COMPILE_BACKTRACKINGPATH #undef CURRENT_AS void PRIV(jit_compile)(const REAL_PCRE *re, PUBL(extra) *extra, int mode) { struct sljit_compiler *compiler; backtrack_common rootbacktrack; compiler_common common_data; compiler_common *common = &common_data; const sljit_u8 *tables = re->tables; pcre_study_data *study; int private_data_size; pcre_uchar *ccend; executable_functions *functions; void *executable_func; sljit_uw executable_size; sljit_uw total_length; label_addr_list *label_addr; struct sljit_label *mainloop_label = NULL; struct sljit_label *continue_match_label; struct sljit_label *empty_match_found_label = NULL; struct sljit_label *empty_match_backtrack_label = NULL; struct sljit_label *reset_match_label; struct sljit_label *quit_label; struct sljit_jump *jump; struct sljit_jump *minlength_check_failed = NULL; struct sljit_jump *reqbyte_notfound = NULL; struct sljit_jump *empty_match = NULL; SLJIT_ASSERT((extra->flags & PCRE_EXTRA_STUDY_DATA) != 0); study = extra->study_data; if (!tables) tables = PRIV(default_tables); memset(&rootbacktrack, 0, sizeof(backtrack_common)); memset(common, 0, sizeof(compiler_common)); rootbacktrack.cc = (pcre_uchar *)re + re->name_table_offset + re->name_count * re->name_entry_size; common->start = rootbacktrack.cc; common->read_only_data_head = NULL; common->fcc = tables + fcc_offset; common->lcc = (sljit_sw)(tables + lcc_offset); common->mode = mode; common->might_be_empty = study->minlength == 0; common->nltype = NLTYPE_FIXED; switch(re->options & PCRE_NEWLINE_BITS) { case 0: /* Compile-time default */ switch(NEWLINE) { case -1: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANY; break; case -2: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANYCRLF; break; default: common->newline = NEWLINE; break; } break; case PCRE_NEWLINE_CR: common->newline = CHAR_CR; break; case PCRE_NEWLINE_LF: common->newline = CHAR_NL; break; case PCRE_NEWLINE_CR+ PCRE_NEWLINE_LF: common->newline = (CHAR_CR << 8) | CHAR_NL; break; case PCRE_NEWLINE_ANY: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANY; break; case PCRE_NEWLINE_ANYCRLF: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANYCRLF; break; default: return; } common->nlmax = READ_CHAR_MAX; common->nlmin = 0; if ((re->options & PCRE_BSR_ANYCRLF) != 0) common->bsr_nltype = NLTYPE_ANYCRLF; else if ((re->options & PCRE_BSR_UNICODE) != 0) common->bsr_nltype = NLTYPE_ANY; else { #ifdef BSR_ANYCRLF common->bsr_nltype = NLTYPE_ANYCRLF; #else common->bsr_nltype = NLTYPE_ANY; #endif } common->bsr_nlmax = READ_CHAR_MAX; common->bsr_nlmin = 0; common->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; common->ctypes = (sljit_sw)(tables + ctypes_offset); common->name_table = ((pcre_uchar *)re) + re->name_table_offset; common->name_count = re->name_count; common->name_entry_size = re->name_entry_size; common->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0; #ifdef SUPPORT_UTF /* PCRE_UTF[16|32] have the same value as PCRE_UTF8. */ common->utf = (re->options & PCRE_UTF8) != 0; #ifdef SUPPORT_UCP common->use_ucp = (re->options & PCRE_UCP) != 0; #endif if (common->utf) { if (common->nltype == NLTYPE_ANY) common->nlmax = 0x2029; else if (common->nltype == NLTYPE_ANYCRLF) common->nlmax = (CHAR_CR > CHAR_NL) ? CHAR_CR : CHAR_NL; else { /* We only care about the first newline character. */ common->nlmax = common->newline & 0xff; } if (common->nltype == NLTYPE_FIXED) common->nlmin = common->newline & 0xff; else common->nlmin = (CHAR_CR < CHAR_NL) ? CHAR_CR : CHAR_NL; if (common->bsr_nltype == NLTYPE_ANY) common->bsr_nlmax = 0x2029; else common->bsr_nlmax = (CHAR_CR > CHAR_NL) ? CHAR_CR : CHAR_NL; common->bsr_nlmin = (CHAR_CR < CHAR_NL) ? CHAR_CR : CHAR_NL; } #endif /* SUPPORT_UTF */ ccend = bracketend(common->start); /* Calculate the local space size on the stack. */ common->ovector_start = LIMIT_MATCH + sizeof(sljit_sw); common->optimized_cbracket = (sljit_u8 *)SLJIT_MALLOC(re->top_bracket + 1, compiler->allocator_data); if (!common->optimized_cbracket) return; #if defined DEBUG_FORCE_UNOPTIMIZED_CBRAS && DEBUG_FORCE_UNOPTIMIZED_CBRAS == 1 memset(common->optimized_cbracket, 0, re->top_bracket + 1); #else memset(common->optimized_cbracket, 1, re->top_bracket + 1); #endif SLJIT_ASSERT(*common->start == OP_BRA && ccend[-(1 + LINK_SIZE)] == OP_KET); #if defined DEBUG_FORCE_UNOPTIMIZED_CBRAS && DEBUG_FORCE_UNOPTIMIZED_CBRAS == 2 common->capture_last_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); #endif if (!check_opcode_types(common, common->start, ccend)) { SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); return; } /* Checking flags and updating ovector_start. */ if (mode == JIT_COMPILE && (re->flags & PCRE_REQCHSET) != 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) { common->req_char_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } if (mode != JIT_COMPILE) { common->start_used_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); if (mode == JIT_PARTIAL_SOFT_COMPILE) { common->hit_start = common->ovector_start; common->ovector_start += 2 * sizeof(sljit_sw); } } if ((re->options & PCRE_FIRSTLINE) != 0) { common->match_end_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } #if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD common->control_head_ptr = 1; #endif if (common->control_head_ptr != 0) { common->control_head_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } if (common->has_set_som) { /* Saving the real start pointer is necessary. */ common->start_ptr = common->ovector_start; common->ovector_start += sizeof(sljit_sw); } /* Aligning ovector to even number of sljit words. */ if ((common->ovector_start & sizeof(sljit_sw)) != 0) common->ovector_start += sizeof(sljit_sw); if (common->start_ptr == 0) common->start_ptr = OVECTOR(0); /* Capturing brackets cannot be optimized if callouts are allowed. */ if (common->capture_last_ptr != 0) memset(common->optimized_cbracket, 0, re->top_bracket + 1); SLJIT_ASSERT(!(common->req_char_ptr != 0 && common->start_used_ptr != 0)); common->cbra_ptr = OVECTOR_START + (re->top_bracket + 1) * 2 * sizeof(sljit_sw); total_length = ccend - common->start; common->private_data_ptrs = (sljit_s32 *)SLJIT_MALLOC(total_length * (sizeof(sljit_s32) + (common->has_then ? 1 : 0)), compiler->allocator_data); if (!common->private_data_ptrs) { SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); return; } memset(common->private_data_ptrs, 0, total_length * sizeof(sljit_s32)); private_data_size = common->cbra_ptr + (re->top_bracket + 1) * sizeof(sljit_sw); set_private_data_ptrs(common, &private_data_size, ccend); if ((re->options & PCRE_ANCHORED) == 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) { if (!detect_fast_forward_skip(common, &private_data_size) && !common->has_skip_in_assert_back) detect_fast_fail(common, common->start, &private_data_size, 4); } SLJIT_ASSERT(common->fast_fail_start_ptr <= common->fast_fail_end_ptr); if (private_data_size > SLJIT_MAX_LOCAL_SIZE) { SLJIT_FREE(common->private_data_ptrs, compiler->allocator_data); SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); return; } if (common->has_then) { common->then_offsets = (sljit_u8 *)(common->private_data_ptrs + total_length); memset(common->then_offsets, 0, total_length); set_then_offsets(common, common->start, NULL); } compiler = sljit_create_compiler(NULL); if (!compiler) { SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); SLJIT_FREE(common->private_data_ptrs, compiler->allocator_data); return; } common->compiler = compiler; /* Main pcre_jit_exec entry. */ sljit_emit_enter(compiler, 0, SLJIT_ARG1(SW), 5, 5, 0, 0, private_data_size); /* Register init. */ reset_ovector(common, (re->top_bracket + 1) * 2); if (common->req_char_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr, SLJIT_R0, 0); OP1(SLJIT_MOV, ARGUMENTS, 0, SLJIT_S0, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_S0, 0); OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, end)); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); OP1(SLJIT_MOV_U32, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, limit_match)); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(struct sljit_stack, end)); OP1(SLJIT_MOV, STACK_LIMIT, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(struct sljit_stack, start)); OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LIMIT_MATCH, TMP1, 0); if (common->fast_fail_start_ptr < common->fast_fail_end_ptr) reset_fast_fail(common); if (mode == JIT_PARTIAL_SOFT_COMPILE) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1); if (common->mark_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, SLJIT_IMM, 0); if (common->control_head_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); /* Main part of the matching */ if ((re->options & PCRE_ANCHORED) == 0) { mainloop_label = mainloop_entry(common, (re->flags & PCRE_HASCRORLF) != 0); continue_match_label = LABEL(); /* Forward search if possible. */ if ((re->options & PCRE_NO_START_OPTIMIZE) == 0) { if (mode == JIT_COMPILE && fast_forward_first_n_chars(common)) ; else if ((re->flags & PCRE_FIRSTSET) != 0) fast_forward_first_char(common, (pcre_uchar)re->first_char, (re->flags & PCRE_FCH_CASELESS) != 0); else if ((re->flags & PCRE_STARTLINE) != 0) fast_forward_newline(common); else if (study != NULL && (study->flags & PCRE_STUDY_MAPPED) != 0) fast_forward_start_bits(common, study->start_bits); } } else continue_match_label = LABEL(); if (mode == JIT_COMPILE && study->minlength > 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) { OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(study->minlength)); minlength_check_failed = CMP(SLJIT_GREATER, TMP2, 0, STR_END, 0); } if (common->req_char_ptr != 0) reqbyte_notfound = search_requested_char(common, (pcre_uchar)re->req_char, (re->flags & PCRE_RCH_CASELESS) != 0, (re->flags & PCRE_FIRSTSET) != 0); /* Store the current STR_PTR in OVECTOR(0). */ OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), STR_PTR, 0); /* Copy the limit of allowed recursions. */ OP1(SLJIT_MOV, COUNT_MATCH, 0, SLJIT_MEM1(SLJIT_SP), LIMIT_MATCH); if (common->capture_last_ptr != 0) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, -1); if (common->fast_forward_bc_ptr != NULL) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), PRIVATE_DATA(common->fast_forward_bc_ptr + 1), STR_PTR, 0); if (common->start_ptr != OVECTOR(0)) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_ptr, STR_PTR, 0); /* Copy the beginning of the string. */ if (mode == JIT_PARTIAL_SOFT_COMPILE) { jump = CMP(SLJIT_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start + sizeof(sljit_sw), STR_PTR, 0); JUMPHERE(jump); } else if (mode == JIT_PARTIAL_HARD_COMPILE) OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); compile_matchingpath(common, common->start, ccend, &rootbacktrack); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) { sljit_free_compiler(compiler); SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); SLJIT_FREE(common->private_data_ptrs, compiler->allocator_data); free_read_only_data(common->read_only_data_head, compiler->allocator_data); return; } if (common->might_be_empty) { empty_match = CMP(SLJIT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); empty_match_found_label = LABEL(); } common->accept_label = LABEL(); if (common->accept != NULL) set_jumps(common->accept, common->accept_label); /* This means we have a match. Update the ovector. */ copy_ovector(common, re->top_bracket + 1); common->quit_label = common->forced_quit_label = LABEL(); if (common->quit != NULL) set_jumps(common->quit, common->quit_label); if (common->forced_quit != NULL) set_jumps(common->forced_quit, common->forced_quit_label); if (minlength_check_failed != NULL) SET_LABEL(minlength_check_failed, common->forced_quit_label); sljit_emit_return(compiler, SLJIT_MOV, SLJIT_RETURN_REG, 0); if (mode != JIT_COMPILE) { common->partialmatchlabel = LABEL(); set_jumps(common->partialmatch, common->partialmatchlabel); return_with_partial_match(common, common->quit_label); } if (common->might_be_empty) empty_match_backtrack_label = LABEL(); compile_backtrackingpath(common, rootbacktrack.top); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) { sljit_free_compiler(compiler); SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); SLJIT_FREE(common->private_data_ptrs, compiler->allocator_data); free_read_only_data(common->read_only_data_head, compiler->allocator_data); return; } SLJIT_ASSERT(rootbacktrack.prev == NULL); reset_match_label = LABEL(); if (mode == JIT_PARTIAL_SOFT_COMPILE) { /* Update hit_start only in the first time. */ jump = CMP(SLJIT_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, -1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, TMP1, 0); JUMPHERE(jump); } /* Check we have remaining characters. */ if ((re->options & PCRE_ANCHORED) == 0 && (re->options & PCRE_FIRSTLINE) != 0) { SLJIT_ASSERT(common->match_end_ptr != 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->match_end_ptr); } OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), (common->fast_forward_bc_ptr != NULL) ? (PRIVATE_DATA(common->fast_forward_bc_ptr + 1)) : common->start_ptr); if ((re->options & PCRE_ANCHORED) == 0) { if (common->ff_newline_shortcut != NULL) { if ((re->options & PCRE_FIRSTLINE) == 0) CMPTO(SLJIT_LESS, STR_PTR, 0, STR_END, 0, common->ff_newline_shortcut); /* There cannot be more newlines here. */ } else CMPTO(SLJIT_LESS, STR_PTR, 0, ((re->options & PCRE_FIRSTLINE) == 0) ? STR_END : TMP1, 0, mainloop_label); } /* No more remaining characters. */ if (reqbyte_notfound != NULL) JUMPHERE(reqbyte_notfound); if (mode == JIT_PARTIAL_SOFT_COMPILE) CMPTO(SLJIT_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1, common->partialmatchlabel); OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); JUMPTO(SLJIT_JUMP, common->quit_label); flush_stubs(common); if (common->might_be_empty) { JUMPHERE(empty_match); OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty)); CMPTO(SLJIT_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0, empty_match_backtrack_label); OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty_atstart)); CMPTO(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, 0, empty_match_found_label); OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); CMPTO(SLJIT_NOT_EQUAL, TMP2, 0, STR_PTR, 0, empty_match_found_label); JUMPTO(SLJIT_JUMP, empty_match_backtrack_label); } common->fast_forward_bc_ptr = NULL; common->fast_fail_start_ptr = 0; common->fast_fail_end_ptr = 0; common->currententry = common->entries; common->local_exit = TRUE; quit_label = common->quit_label; while (common->currententry != NULL) { /* Might add new entries. */ compile_recurse(common); if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) { sljit_free_compiler(compiler); SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); SLJIT_FREE(common->private_data_ptrs, compiler->allocator_data); free_read_only_data(common->read_only_data_head, compiler->allocator_data); return; } flush_stubs(common); common->currententry = common->currententry->next; } common->local_exit = FALSE; common->quit_label = quit_label; /* Allocating stack, returns with PCRE_ERROR_JIT_STACKLIMIT if fails. */ /* This is a (really) rare case. */ set_jumps(common->stackalloc, LABEL()); /* RETURN_ADDR is not a saved register. */ sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); SLJIT_ASSERT(TMP1 == SLJIT_R0 && STACK_TOP == SLJIT_R1); OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, STACK_TOP, 0); OP1(SLJIT_MOV, SLJIT_R0, 0, ARGUMENTS, 0); OP2(SLJIT_SUB, SLJIT_R1, 0, STACK_LIMIT, 0, SLJIT_IMM, STACK_GROWTH_RATE); OP1(SLJIT_MOV, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, stack)); OP1(SLJIT_MOV, STACK_LIMIT, 0, TMP2, 0); sljit_emit_icall(compiler, SLJIT_CALL, SLJIT_RET(SW) | SLJIT_ARG1(SW) | SLJIT_ARG2(SW), SLJIT_IMM, SLJIT_FUNC_OFFSET(sljit_stack_resize)); jump = CMP(SLJIT_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0); OP1(SLJIT_MOV, TMP2, 0, STACK_LIMIT, 0); OP1(SLJIT_MOV, STACK_LIMIT, 0, SLJIT_RETURN_REG, 0); OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); sljit_emit_fast_return(compiler, TMP1, 0); /* Allocation failed. */ JUMPHERE(jump); /* We break the return address cache here, but this is a really rare case. */ OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_JIT_STACKLIMIT); JUMPTO(SLJIT_JUMP, common->quit_label); /* Call limit reached. */ set_jumps(common->calllimit, LABEL()); OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_MATCHLIMIT); JUMPTO(SLJIT_JUMP, common->quit_label); if (common->revertframes != NULL) { set_jumps(common->revertframes, LABEL()); do_revertframes(common); } if (common->wordboundary != NULL) { set_jumps(common->wordboundary, LABEL()); check_wordboundary(common); } if (common->anynewline != NULL) { set_jumps(common->anynewline, LABEL()); check_anynewline(common); } if (common->hspace != NULL) { set_jumps(common->hspace, LABEL()); check_hspace(common); } if (common->vspace != NULL) { set_jumps(common->vspace, LABEL()); check_vspace(common); } if (common->casefulcmp != NULL) { set_jumps(common->casefulcmp, LABEL()); do_casefulcmp(common); } if (common->caselesscmp != NULL) { set_jumps(common->caselesscmp, LABEL()); do_caselesscmp(common); } if (common->reset_match != NULL) { set_jumps(common->reset_match, LABEL()); do_reset_match(common, (re->top_bracket + 1) * 2); CMPTO(SLJIT_GREATER, STR_PTR, 0, TMP1, 0, continue_match_label); OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); JUMPTO(SLJIT_JUMP, reset_match_label); } #ifdef SUPPORT_UTF #ifdef COMPILE_PCRE8 if (common->utfreadchar != NULL) { set_jumps(common->utfreadchar, LABEL()); do_utfreadchar(common); } if (common->utfreadchar16 != NULL) { set_jumps(common->utfreadchar16, LABEL()); do_utfreadchar16(common); } if (common->utfreadtype8 != NULL) { set_jumps(common->utfreadtype8, LABEL()); do_utfreadtype8(common); } #endif /* COMPILE_PCRE8 */ #endif /* SUPPORT_UTF */ #ifdef SUPPORT_UCP if (common->getucd != NULL) { set_jumps(common->getucd, LABEL()); do_getucd(common); } #endif SLJIT_FREE(common->optimized_cbracket, compiler->allocator_data); SLJIT_FREE(common->private_data_ptrs, compiler->allocator_data); executable_func = sljit_generate_code(compiler); executable_size = sljit_get_generated_code_size(compiler); label_addr = common->label_addrs; while (label_addr != NULL) { *label_addr->update_addr = sljit_get_label_addr(label_addr->label); label_addr = label_addr->next; } sljit_free_compiler(compiler); if (executable_func == NULL) { free_read_only_data(common->read_only_data_head, compiler->allocator_data); return; } /* Reuse the function descriptor if possible. */ if ((extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && extra->executable_jit != NULL) functions = (executable_functions *)extra->executable_jit; else { /* Note: If your memory-checker has flagged the allocation below as a * memory leak, it is probably because you either forgot to call * pcre_free_study() (or pcre16_free_study()) on the pcre_extra (or * pcre16_extra) object, or you called said function after having * cleared the PCRE_EXTRA_EXECUTABLE_JIT bit from the "flags" field * of the object. (The function will only free the JIT data if the * bit remains set, as the bit indicates that the pointer to the data * is valid.) */ functions = SLJIT_MALLOC(sizeof(executable_functions), compiler->allocator_data); if (functions == NULL) { /* This case is highly unlikely since we just recently freed a lot of memory. Not impossible though. */ sljit_free_code(executable_func); free_read_only_data(common->read_only_data_head, compiler->allocator_data); return; } memset(functions, 0, sizeof(executable_functions)); functions->top_bracket = (re->top_bracket + 1) * 2; functions->limit_match = (re->flags & PCRE_MLSET) != 0 ? re->limit_match : 0; extra->executable_jit = functions; extra->flags |= PCRE_EXTRA_EXECUTABLE_JIT; } functions->executable_funcs[mode] = executable_func; functions->read_only_data_heads[mode] = common->read_only_data_head; functions->executable_sizes[mode] = executable_size; } static SLJIT_NOINLINE int jit_machine_stack_exec(jit_arguments *arguments, void *executable_func) { union { void *executable_func; jit_function call_executable_func; } convert_executable_func; sljit_u8 local_space[MACHINE_STACK_SIZE]; struct sljit_stack local_stack; local_stack.min_start = local_space; local_stack.start = local_space; local_stack.end = local_space + MACHINE_STACK_SIZE; local_stack.top = local_space + MACHINE_STACK_SIZE; arguments->stack = &local_stack; convert_executable_func.executable_func = executable_func; return convert_executable_func.call_executable_func(arguments); } int PRIV(jit_exec)(const PUBL(extra) *extra_data, const pcre_uchar *subject, int length, int start_offset, int options, int *offsets, int offset_count) { executable_functions *functions = (executable_functions *)extra_data->executable_jit; union { void *executable_func; jit_function call_executable_func; } convert_executable_func; jit_arguments arguments; int max_offset_count; int retval; int mode = JIT_COMPILE; if ((options & PCRE_PARTIAL_HARD) != 0) mode = JIT_PARTIAL_HARD_COMPILE; else if ((options & PCRE_PARTIAL_SOFT) != 0) mode = JIT_PARTIAL_SOFT_COMPILE; if (functions->executable_funcs[mode] == NULL) return PCRE_ERROR_JIT_BADOPTION; /* Sanity checks should be handled by pcre_exec. */ arguments.str = subject + start_offset; arguments.begin = subject; arguments.end = subject + length; arguments.mark_ptr = NULL; /* JIT decreases this value less frequently than the interpreter. */ arguments.limit_match = ((extra_data->flags & PCRE_EXTRA_MATCH_LIMIT) == 0) ? MATCH_LIMIT : (sljit_u32)(extra_data->match_limit); if (functions->limit_match != 0 && functions->limit_match < arguments.limit_match) arguments.limit_match = functions->limit_match; arguments.notbol = (options & PCRE_NOTBOL) != 0; arguments.noteol = (options & PCRE_NOTEOL) != 0; arguments.notempty = (options & PCRE_NOTEMPTY) != 0; arguments.notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; arguments.offsets = offsets; arguments.callout_data = (extra_data->flags & PCRE_EXTRA_CALLOUT_DATA) != 0 ? extra_data->callout_data : NULL; arguments.real_offset_count = offset_count; /* pcre_exec() rounds offset_count to a multiple of 3, and then uses only 2/3 of the output vector for storing captured strings, with the remainder used as workspace. We don't need the workspace here. For compatibility, we limit the number of captured strings in the same way as pcre_exec(), so that the user gets the same result with and without JIT. */ if (offset_count != 2) offset_count = ((offset_count - (offset_count % 3)) * 2) / 3; max_offset_count = functions->top_bracket; if (offset_count > max_offset_count) offset_count = max_offset_count; arguments.offset_count = offset_count; if (functions->callback) arguments.stack = (struct sljit_stack *)functions->callback(functions->userdata); else arguments.stack = (struct sljit_stack *)functions->userdata; if (arguments.stack == NULL) retval = jit_machine_stack_exec(&arguments, functions->executable_funcs[mode]); else { convert_executable_func.executable_func = functions->executable_funcs[mode]; retval = convert_executable_func.call_executable_func(&arguments); } if (retval * 2 > offset_count) retval = 0; if ((extra_data->flags & PCRE_EXTRA_MARK) != 0) *(extra_data->mark) = arguments.mark_ptr; return retval; } #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_jit_exec(const pcre *argument_re, const pcre_extra *extra_data, PCRE_SPTR subject, int length, int start_offset, int options, int *offsets, int offset_count, pcre_jit_stack *stack) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_jit_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets, int offset_count, pcre16_jit_stack *stack) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_jit_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets, int offset_count, pcre32_jit_stack *stack) #endif { pcre_uchar *subject_ptr = (pcre_uchar *)subject; executable_functions *functions = (executable_functions *)extra_data->executable_jit; union { void *executable_func; jit_function call_executable_func; } convert_executable_func; jit_arguments arguments; int max_offset_count; int retval; int mode = JIT_COMPILE; SLJIT_UNUSED_ARG(argument_re); /* Plausibility checks */ if ((options & ~PUBLIC_JIT_EXEC_OPTIONS) != 0) return PCRE_ERROR_JIT_BADOPTION; if ((options & PCRE_PARTIAL_HARD) != 0) mode = JIT_PARTIAL_HARD_COMPILE; else if ((options & PCRE_PARTIAL_SOFT) != 0) mode = JIT_PARTIAL_SOFT_COMPILE; if (functions == NULL || functions->executable_funcs[mode] == NULL) return PCRE_ERROR_JIT_BADOPTION; /* Sanity checks should be handled by pcre_exec. */ arguments.stack = (struct sljit_stack *)stack; arguments.str = subject_ptr + start_offset; arguments.begin = subject_ptr; arguments.end = subject_ptr + length; arguments.mark_ptr = NULL; /* JIT decreases this value less frequently than the interpreter. */ arguments.limit_match = ((extra_data->flags & PCRE_EXTRA_MATCH_LIMIT) == 0) ? MATCH_LIMIT : (sljit_u32)(extra_data->match_limit); if (functions->limit_match != 0 && functions->limit_match < arguments.limit_match) arguments.limit_match = functions->limit_match; arguments.notbol = (options & PCRE_NOTBOL) != 0; arguments.noteol = (options & PCRE_NOTEOL) != 0; arguments.notempty = (options & PCRE_NOTEMPTY) != 0; arguments.notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; arguments.offsets = offsets; arguments.callout_data = (extra_data->flags & PCRE_EXTRA_CALLOUT_DATA) != 0 ? extra_data->callout_data : NULL; arguments.real_offset_count = offset_count; /* pcre_exec() rounds offset_count to a multiple of 3, and then uses only 2/3 of the output vector for storing captured strings, with the remainder used as workspace. We don't need the workspace here. For compatibility, we limit the number of captured strings in the same way as pcre_exec(), so that the user gets the same result with and without JIT. */ if (offset_count != 2) offset_count = ((offset_count - (offset_count % 3)) * 2) / 3; max_offset_count = functions->top_bracket; if (offset_count > max_offset_count) offset_count = max_offset_count; arguments.offset_count = offset_count; convert_executable_func.executable_func = functions->executable_funcs[mode]; retval = convert_executable_func.call_executable_func(&arguments); if (retval * 2 > offset_count) retval = 0; if ((extra_data->flags & PCRE_EXTRA_MARK) != 0) *(extra_data->mark) = arguments.mark_ptr; return retval; } void PRIV(jit_free)(void *executable_funcs) { int i; executable_functions *functions = (executable_functions *)executable_funcs; for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) { if (functions->executable_funcs[i] != NULL) sljit_free_code(functions->executable_funcs[i]); free_read_only_data(functions->read_only_data_heads[i], NULL); } SLJIT_FREE(functions, compiler->allocator_data); } int PRIV(jit_get_size)(void *executable_funcs) { int i; sljit_uw size = 0; sljit_uw *executable_sizes = ((executable_functions *)executable_funcs)->executable_sizes; for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) size += executable_sizes[i]; return (int)size; } const char* PRIV(jit_get_target)(void) { return sljit_get_platform_name(); } #if defined COMPILE_PCRE8 PCRE_EXP_DECL pcre_jit_stack * pcre_jit_stack_alloc(int startsize, int maxsize) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL pcre16_jit_stack * pcre16_jit_stack_alloc(int startsize, int maxsize) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL pcre32_jit_stack * pcre32_jit_stack_alloc(int startsize, int maxsize) #endif { if (startsize < 1 || maxsize < 1) return NULL; if (startsize > maxsize) startsize = maxsize; startsize = (startsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); maxsize = (maxsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); return (PUBL(jit_stack)*)sljit_allocate_stack(startsize, maxsize, NULL); } #if defined COMPILE_PCRE8 PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *stack) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *stack) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL void pcre32_jit_stack_free(pcre32_jit_stack *stack) #endif { sljit_free_stack((struct sljit_stack *)stack, NULL); } #if defined COMPILE_PCRE8 PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *extra, pcre_jit_callback callback, void *userdata) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *extra, pcre16_jit_callback callback, void *userdata) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL void pcre32_assign_jit_stack(pcre32_extra *extra, pcre32_jit_callback callback, void *userdata) #endif { executable_functions *functions; if (extra != NULL && (extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && extra->executable_jit != NULL) { functions = (executable_functions *)extra->executable_jit; functions->callback = callback; functions->userdata = userdata; } } #if defined COMPILE_PCRE8 PCRE_EXP_DECL void pcre_jit_free_unused_memory(void) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL void pcre16_jit_free_unused_memory(void) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL void pcre32_jit_free_unused_memory(void) #endif { sljit_free_unused_memory_exec(); } #else /* SUPPORT_JIT */ /* These are dummy functions to avoid linking errors when JIT support is not being compiled. */ #if defined COMPILE_PCRE8 PCRE_EXP_DECL pcre_jit_stack * pcre_jit_stack_alloc(int startsize, int maxsize) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL pcre16_jit_stack * pcre16_jit_stack_alloc(int startsize, int maxsize) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL pcre32_jit_stack * pcre32_jit_stack_alloc(int startsize, int maxsize) #endif { (void)startsize; (void)maxsize; return NULL; } #if defined COMPILE_PCRE8 PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *stack) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *stack) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL void pcre32_jit_stack_free(pcre32_jit_stack *stack) #endif { (void)stack; } #if defined COMPILE_PCRE8 PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *extra, pcre_jit_callback callback, void *userdata) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *extra, pcre16_jit_callback callback, void *userdata) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL void pcre32_assign_jit_stack(pcre32_extra *extra, pcre32_jit_callback callback, void *userdata) #endif { (void)extra; (void)callback; (void)userdata; } #if defined COMPILE_PCRE8 PCRE_EXP_DECL void pcre_jit_free_unused_memory(void) #elif defined COMPILE_PCRE16 PCRE_EXP_DECL void pcre16_jit_free_unused_memory(void) #elif defined COMPILE_PCRE32 PCRE_EXP_DECL void pcre32_jit_free_unused_memory(void) #endif { } #endif /* End of pcre_jit_compile.c */
libgit2-main
deps/pcre/pcre_jit_compile.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2012 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This module contains some convenience functions for extracting substrings from the subject string after a regex match has succeeded. The original idea for these functions came from Scott Wimer. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pcre_internal.h" /************************************************* * Find number for named string * *************************************************/ /* This function is used by the get_first_set() function below, as well as being generally available. It assumes that names are unique. Arguments: code the compiled regex stringname the name whose number is required Returns: the number of the named parentheses, or a negative number (PCRE_ERROR_NOSUBSTRING) if not found */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_get_stringnumber(const pcre *code, const char *stringname) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_get_stringnumber(const pcre16 *code, PCRE_SPTR16 stringname) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_get_stringnumber(const pcre32 *code, PCRE_SPTR32 stringname) #endif { int rc; int entrysize; int top, bot; pcre_uchar *nametable; #ifdef COMPILE_PCRE8 if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) return rc; if (top <= 0) return PCRE_ERROR_NOSUBSTRING; if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) return rc; if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) return rc; #endif #ifdef COMPILE_PCRE16 if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) return rc; if (top <= 0) return PCRE_ERROR_NOSUBSTRING; if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) return rc; if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) return rc; #endif #ifdef COMPILE_PCRE32 if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) return rc; if (top <= 0) return PCRE_ERROR_NOSUBSTRING; if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) return rc; if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) return rc; #endif bot = 0; while (top > bot) { int mid = (top + bot) / 2; pcre_uchar *entry = nametable + entrysize*mid; int c = STRCMP_UC_UC((pcre_uchar *)stringname, (pcre_uchar *)(entry + IMM2_SIZE)); if (c == 0) return GET2(entry, 0); if (c > 0) bot = mid + 1; else top = mid; } return PCRE_ERROR_NOSUBSTRING; } /************************************************* * Find (multiple) entries for named string * *************************************************/ /* This is used by the get_first_set() function below, as well as being generally available. It is used when duplicated names are permitted. Arguments: code the compiled regex stringname the name whose entries required firstptr where to put the pointer to the first entry lastptr where to put the pointer to the last entry Returns: the length of each entry, or a negative number (PCRE_ERROR_NOSUBSTRING) if not found */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_get_stringtable_entries(const pcre *code, const char *stringname, char **firstptr, char **lastptr) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_get_stringtable_entries(const pcre16 *code, PCRE_SPTR16 stringname, PCRE_UCHAR16 **firstptr, PCRE_UCHAR16 **lastptr) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_get_stringtable_entries(const pcre32 *code, PCRE_SPTR32 stringname, PCRE_UCHAR32 **firstptr, PCRE_UCHAR32 **lastptr) #endif { int rc; int entrysize; int top, bot; pcre_uchar *nametable, *lastentry; #ifdef COMPILE_PCRE8 if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) return rc; if (top <= 0) return PCRE_ERROR_NOSUBSTRING; if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) return rc; if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) return rc; #endif #ifdef COMPILE_PCRE16 if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) return rc; if (top <= 0) return PCRE_ERROR_NOSUBSTRING; if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) return rc; if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) return rc; #endif #ifdef COMPILE_PCRE32 if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) return rc; if (top <= 0) return PCRE_ERROR_NOSUBSTRING; if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) return rc; if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) return rc; #endif lastentry = nametable + entrysize * (top - 1); bot = 0; while (top > bot) { int mid = (top + bot) / 2; pcre_uchar *entry = nametable + entrysize*mid; int c = STRCMP_UC_UC((pcre_uchar *)stringname, (pcre_uchar *)(entry + IMM2_SIZE)); if (c == 0) { pcre_uchar *first = entry; pcre_uchar *last = entry; while (first > nametable) { if (STRCMP_UC_UC((pcre_uchar *)stringname, (pcre_uchar *)(first - entrysize + IMM2_SIZE)) != 0) break; first -= entrysize; } while (last < lastentry) { if (STRCMP_UC_UC((pcre_uchar *)stringname, (pcre_uchar *)(last + entrysize + IMM2_SIZE)) != 0) break; last += entrysize; } #if defined COMPILE_PCRE8 *firstptr = (char *)first; *lastptr = (char *)last; #elif defined COMPILE_PCRE16 *firstptr = (PCRE_UCHAR16 *)first; *lastptr = (PCRE_UCHAR16 *)last; #elif defined COMPILE_PCRE32 *firstptr = (PCRE_UCHAR32 *)first; *lastptr = (PCRE_UCHAR32 *)last; #endif return entrysize; } if (c > 0) bot = mid + 1; else top = mid; } return PCRE_ERROR_NOSUBSTRING; } /************************************************* * Find first set of multiple named strings * *************************************************/ /* This function allows for duplicate names in the table of named substrings. It returns the number of the first one that was set in a pattern match. Arguments: code the compiled regex stringname the name of the capturing substring ovector the vector of matched substrings stringcount number of captured substrings Returns: the number of the first that is set, or the number of the last one if none are set, or a negative number on error */ #if defined COMPILE_PCRE8 static int get_first_set(const pcre *code, const char *stringname, int *ovector, int stringcount) #elif defined COMPILE_PCRE16 static int get_first_set(const pcre16 *code, PCRE_SPTR16 stringname, int *ovector, int stringcount) #elif defined COMPILE_PCRE32 static int get_first_set(const pcre32 *code, PCRE_SPTR32 stringname, int *ovector, int stringcount) #endif { const REAL_PCRE *re = (const REAL_PCRE *)code; int entrysize; pcre_uchar *entry; #if defined COMPILE_PCRE8 char *first, *last; #elif defined COMPILE_PCRE16 PCRE_UCHAR16 *first, *last; #elif defined COMPILE_PCRE32 PCRE_UCHAR32 *first, *last; #endif #if defined COMPILE_PCRE8 if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) return pcre_get_stringnumber(code, stringname); entrysize = pcre_get_stringtable_entries(code, stringname, &first, &last); #elif defined COMPILE_PCRE16 if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) return pcre16_get_stringnumber(code, stringname); entrysize = pcre16_get_stringtable_entries(code, stringname, &first, &last); #elif defined COMPILE_PCRE32 if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) return pcre32_get_stringnumber(code, stringname); entrysize = pcre32_get_stringtable_entries(code, stringname, &first, &last); #endif if (entrysize <= 0) return entrysize; for (entry = (pcre_uchar *)first; entry <= (pcre_uchar *)last; entry += entrysize) { int n = GET2(entry, 0); if (n < stringcount && ovector[n*2] >= 0) return n; } return GET2(entry, 0); } /************************************************* * Copy captured string to given buffer * *************************************************/ /* This function copies a single captured substring into a given buffer. Note that we use memcpy() rather than strncpy() in case there are binary zeros in the string. Arguments: subject the subject string that was matched ovector pointer to the offsets table stringcount the number of substrings that were captured (i.e. the yield of the pcre_exec call, unless that was zero, in which case it should be 1/3 of the offset table size) stringnumber the number of the required substring buffer where to put the substring size the size of the buffer Returns: if successful: the length of the copied string, not including the zero that is put on the end; can be zero if not successful: PCRE_ERROR_NOMEMORY (-6) buffer too small PCRE_ERROR_NOSUBSTRING (-7) no such captured substring */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_copy_substring(const char *subject, int *ovector, int stringcount, int stringnumber, char *buffer, int size) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_copy_substring(PCRE_SPTR16 subject, int *ovector, int stringcount, int stringnumber, PCRE_UCHAR16 *buffer, int size) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_copy_substring(PCRE_SPTR32 subject, int *ovector, int stringcount, int stringnumber, PCRE_UCHAR32 *buffer, int size) #endif { int yield; if (stringnumber < 0 || stringnumber >= stringcount) return PCRE_ERROR_NOSUBSTRING; stringnumber *= 2; yield = ovector[stringnumber+1] - ovector[stringnumber]; if (size < yield + 1) return PCRE_ERROR_NOMEMORY; memcpy(buffer, subject + ovector[stringnumber], IN_UCHARS(yield)); buffer[yield] = 0; return yield; } /************************************************* * Copy named captured string to given buffer * *************************************************/ /* This function copies a single captured substring into a given buffer, identifying it by name. If the regex permits duplicate names, the first substring that is set is chosen. Arguments: code the compiled regex subject the subject string that was matched ovector pointer to the offsets table stringcount the number of substrings that were captured (i.e. the yield of the pcre_exec call, unless that was zero, in which case it should be 1/3 of the offset table size) stringname the name of the required substring buffer where to put the substring size the size of the buffer Returns: if successful: the length of the copied string, not including the zero that is put on the end; can be zero if not successful: PCRE_ERROR_NOMEMORY (-6) buffer too small PCRE_ERROR_NOSUBSTRING (-7) no such captured substring */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_copy_named_substring(const pcre *code, const char *subject, int *ovector, int stringcount, const char *stringname, char *buffer, int size) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_copy_named_substring(const pcre16 *code, PCRE_SPTR16 subject, int *ovector, int stringcount, PCRE_SPTR16 stringname, PCRE_UCHAR16 *buffer, int size) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_copy_named_substring(const pcre32 *code, PCRE_SPTR32 subject, int *ovector, int stringcount, PCRE_SPTR32 stringname, PCRE_UCHAR32 *buffer, int size) #endif { int n = get_first_set(code, stringname, ovector, stringcount); if (n <= 0) return n; #if defined COMPILE_PCRE8 return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size); #elif defined COMPILE_PCRE16 return pcre16_copy_substring(subject, ovector, stringcount, n, buffer, size); #elif defined COMPILE_PCRE32 return pcre32_copy_substring(subject, ovector, stringcount, n, buffer, size); #endif } /************************************************* * Copy all captured strings to new store * *************************************************/ /* This function gets one chunk of store and builds a list of pointers and all of the captured substrings in it. A NULL pointer is put on the end of the list. Arguments: subject the subject string that was matched ovector pointer to the offsets table stringcount the number of substrings that were captured (i.e. the yield of the pcre_exec call, unless that was zero, in which case it should be 1/3 of the offset table size) listptr set to point to the list of pointers Returns: if successful: 0 if not successful: PCRE_ERROR_NOMEMORY (-6) failed to get store */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_get_substring_list(const char *subject, int *ovector, int stringcount, const char ***listptr) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_get_substring_list(PCRE_SPTR16 subject, int *ovector, int stringcount, PCRE_SPTR16 **listptr) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_get_substring_list(PCRE_SPTR32 subject, int *ovector, int stringcount, PCRE_SPTR32 **listptr) #endif { int i; int size = sizeof(pcre_uchar *); int double_count = stringcount * 2; pcre_uchar **stringlist; pcre_uchar *p; for (i = 0; i < double_count; i += 2) { size += sizeof(pcre_uchar *) + IN_UCHARS(1); if (ovector[i+1] > ovector[i]) size += IN_UCHARS(ovector[i+1] - ovector[i]); } stringlist = (pcre_uchar **)(PUBL(malloc))(size); if (stringlist == NULL) return PCRE_ERROR_NOMEMORY; #if defined COMPILE_PCRE8 *listptr = (const char **)stringlist; #elif defined COMPILE_PCRE16 *listptr = (PCRE_SPTR16 *)stringlist; #elif defined COMPILE_PCRE32 *listptr = (PCRE_SPTR32 *)stringlist; #endif p = (pcre_uchar *)(stringlist + stringcount + 1); for (i = 0; i < double_count; i += 2) { int len = (ovector[i+1] > ovector[i])? (ovector[i+1] - ovector[i]) : 0; memcpy(p, subject + ovector[i], IN_UCHARS(len)); *stringlist++ = p; p += len; *p++ = 0; } *stringlist = NULL; return 0; } /************************************************* * Free store obtained by get_substring_list * *************************************************/ /* This function exists for the benefit of people calling PCRE from non-C programs that can call its functions, but not free() or (PUBL(free))() directly. Argument: the result of a previous pcre_get_substring_list() Returns: nothing */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN void PCRE_CALL_CONVENTION pcre_free_substring_list(const char **pointer) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN void PCRE_CALL_CONVENTION pcre16_free_substring_list(PCRE_SPTR16 *pointer) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN void PCRE_CALL_CONVENTION pcre32_free_substring_list(PCRE_SPTR32 *pointer) #endif { (PUBL(free))((void *)pointer); } /************************************************* * Copy captured string to new store * *************************************************/ /* This function copies a single captured substring into a piece of new store Arguments: subject the subject string that was matched ovector pointer to the offsets table stringcount the number of substrings that were captured (i.e. the yield of the pcre_exec call, unless that was zero, in which case it should be 1/3 of the offset table size) stringnumber the number of the required substring stringptr where to put a pointer to the substring Returns: if successful: the length of the string, not including the zero that is put on the end; can be zero if not successful: PCRE_ERROR_NOMEMORY (-6) failed to get store PCRE_ERROR_NOSUBSTRING (-7) substring not present */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_get_substring(const char *subject, int *ovector, int stringcount, int stringnumber, const char **stringptr) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_get_substring(PCRE_SPTR16 subject, int *ovector, int stringcount, int stringnumber, PCRE_SPTR16 *stringptr) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_get_substring(PCRE_SPTR32 subject, int *ovector, int stringcount, int stringnumber, PCRE_SPTR32 *stringptr) #endif { int yield; pcre_uchar *substring; if (stringnumber < 0 || stringnumber >= stringcount) return PCRE_ERROR_NOSUBSTRING; stringnumber *= 2; yield = ovector[stringnumber+1] - ovector[stringnumber]; substring = (pcre_uchar *)(PUBL(malloc))(IN_UCHARS(yield + 1)); if (substring == NULL) return PCRE_ERROR_NOMEMORY; memcpy(substring, subject + ovector[stringnumber], IN_UCHARS(yield)); substring[yield] = 0; #if defined COMPILE_PCRE8 *stringptr = (const char *)substring; #elif defined COMPILE_PCRE16 *stringptr = (PCRE_SPTR16)substring; #elif defined COMPILE_PCRE32 *stringptr = (PCRE_SPTR32)substring; #endif return yield; } /************************************************* * Copy named captured string to new store * *************************************************/ /* This function copies a single captured substring, identified by name, into new store. If the regex permits duplicate names, the first substring that is set is chosen. Arguments: code the compiled regex subject the subject string that was matched ovector pointer to the offsets table stringcount the number of substrings that were captured (i.e. the yield of the pcre_exec call, unless that was zero, in which case it should be 1/3 of the offset table size) stringname the name of the required substring stringptr where to put the pointer Returns: if successful: the length of the copied string, not including the zero that is put on the end; can be zero if not successful: PCRE_ERROR_NOMEMORY (-6) couldn't get memory PCRE_ERROR_NOSUBSTRING (-7) no such captured substring */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre_get_named_substring(const pcre *code, const char *subject, int *ovector, int stringcount, const char *stringname, const char **stringptr) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre16_get_named_substring(const pcre16 *code, PCRE_SPTR16 subject, int *ovector, int stringcount, PCRE_SPTR16 stringname, PCRE_SPTR16 *stringptr) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION pcre32_get_named_substring(const pcre32 *code, PCRE_SPTR32 subject, int *ovector, int stringcount, PCRE_SPTR32 stringname, PCRE_SPTR32 *stringptr) #endif { int n = get_first_set(code, stringname, ovector, stringcount); if (n <= 0) return n; #if defined COMPILE_PCRE8 return pcre_get_substring(subject, ovector, stringcount, n, stringptr); #elif defined COMPILE_PCRE16 return pcre16_get_substring(subject, ovector, stringcount, n, stringptr); #elif defined COMPILE_PCRE32 return pcre32_get_substring(subject, ovector, stringcount, n, stringptr); #endif } /************************************************* * Free store obtained by get_substring * *************************************************/ /* This function exists for the benefit of people calling PCRE from non-C programs that can call its functions, but not free() or (PUBL(free))() directly. Argument: the result of a previous pcre_get_substring() Returns: nothing */ #if defined COMPILE_PCRE8 PCRE_EXP_DEFN void PCRE_CALL_CONVENTION pcre_free_substring(const char *pointer) #elif defined COMPILE_PCRE16 PCRE_EXP_DEFN void PCRE_CALL_CONVENTION pcre16_free_substring(PCRE_SPTR16 pointer) #elif defined COMPILE_PCRE32 PCRE_EXP_DEFN void PCRE_CALL_CONVENTION pcre32_free_substring(PCRE_SPTR32 pointer) #endif { (PUBL(free))((void *)pointer); } /* End of pcre_get.c */
libgit2-main
deps/pcre/pcre_get.c
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2012 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This module contains a PCRE private debugging function for printing out the internal form of a compiled regular expression, along with some supporting local functions. This source file is used in two places: (1) It is #included by pcre_compile.c when it is compiled in debugging mode (PCRE_DEBUG defined in pcre_internal.h). It is not included in production compiles. In this case PCRE_INCLUDED is defined. (2) It is also compiled separately and linked with pcretest.c, which can be asked to print out a compiled regex for debugging purposes. */ #ifndef PCRE_INCLUDED #ifdef HAVE_CONFIG_H #include "config.h" #endif /* For pcretest program. */ #define PRIV(name) name /* We have to include pcre_internal.h because we need the internal info for displaying the results of pcre_study() and we also need to know about the internal macros, structures, and other internal data values; pcretest has "inside information" compared to a program that strictly follows the PCRE API. Although pcre_internal.h does itself include pcre.h, we explicitly include it here before pcre_internal.h so that the PCRE_EXP_xxx macros get set appropriately for an application, not for building PCRE. */ #include "pcre.h" #include "pcre_internal.h" /* These are the funtions that are contained within. It doesn't seem worth having a separate .h file just for this. */ #endif /* PCRE_INCLUDED */ #ifdef PCRE_INCLUDED static /* Keep the following function as private. */ #endif #if defined COMPILE_PCRE8 void pcre_printint(pcre *external_re, FILE *f, BOOL print_lengths); #elif defined COMPILE_PCRE16 void pcre16_printint(pcre *external_re, FILE *f, BOOL print_lengths); #elif defined COMPILE_PCRE32 void pcre32_printint(pcre *external_re, FILE *f, BOOL print_lengths); #endif /* Macro that decides whether a character should be output as a literal or in hexadecimal. We don't use isprint() because that can vary from system to system (even without the use of locales) and we want the output always to be the same, for testing purposes. */ #ifdef EBCDIC #define PRINTABLE(c) ((c) >= 64 && (c) < 255) #else #define PRINTABLE(c) ((c) >= 32 && (c) < 127) #endif /* The table of operator names. */ static const char *priv_OP_names[] = { OP_NAME_LIST }; /* This table of operator lengths is not actually used by the working code, but its size is needed for a check that ensures it is the correct size for the number of opcodes (thus catching update omissions). */ static const pcre_uint8 priv_OP_lengths[] = { OP_LENGTHS }; /************************************************* * Print single- or multi-byte character * *************************************************/ static unsigned int print_char(FILE *f, pcre_uchar *ptr, BOOL utf) { pcre_uint32 c = *ptr; #ifndef SUPPORT_UTF (void)utf; /* Avoid compiler warning */ if (PRINTABLE(c)) fprintf(f, "%c", (char)c); else if (c <= 0x80) fprintf(f, "\\x%02x", c); else fprintf(f, "\\x{%x}", c); return 0; #else #if defined COMPILE_PCRE8 if (!utf || (c & 0xc0) != 0xc0) { if (PRINTABLE(c)) fprintf(f, "%c", (char)c); else if (c < 0x80) fprintf(f, "\\x%02x", c); else fprintf(f, "\\x{%02x}", c); return 0; } else { int i; int a = PRIV(utf8_table4)[c & 0x3f]; /* Number of additional bytes */ int s = 6*a; c = (c & PRIV(utf8_table3)[a]) << s; for (i = 1; i <= a; i++) { /* This is a check for malformed UTF-8; it should only occur if the sanity check has been turned off. Rather than swallow random bytes, just stop if we hit a bad one. Print it with \X instead of \x as an indication. */ if ((ptr[i] & 0xc0) != 0x80) { fprintf(f, "\\X{%x}", c); return i - 1; } /* The byte is OK */ s -= 6; c |= (ptr[i] & 0x3f) << s; } fprintf(f, "\\x{%x}", c); return a; } #elif defined COMPILE_PCRE16 if (!utf || (c & 0xfc00) != 0xd800) { if (PRINTABLE(c)) fprintf(f, "%c", (char)c); else if (c <= 0x80) fprintf(f, "\\x%02x", c); else fprintf(f, "\\x{%02x}", c); return 0; } else { /* This is a check for malformed UTF-16; it should only occur if the sanity check has been turned off. Rather than swallow a low surrogate, just stop if we hit a bad one. Print it with \X instead of \x as an indication. */ if ((ptr[1] & 0xfc00) != 0xdc00) { fprintf(f, "\\X{%x}", c); return 0; } c = (((c & 0x3ff) << 10) | (ptr[1] & 0x3ff)) + 0x10000; fprintf(f, "\\x{%x}", c); return 1; } #elif defined COMPILE_PCRE32 if (!utf || (c & 0xfffff800u) != 0xd800u) { if (PRINTABLE(c)) fprintf(f, "%c", (char)c); else if (c <= 0x80) fprintf(f, "\\x%02x", c); else fprintf(f, "\\x{%x}", c); return 0; } else { /* This is a check for malformed UTF-32; it should only occur if the sanity check has been turned off. Rather than swallow a surrogate, just stop if we hit one. Print it with \X instead of \x as an indication. */ fprintf(f, "\\X{%x}", c); return 0; } #endif /* COMPILE_PCRE[8|16|32] */ #endif /* SUPPORT_UTF */ } /************************************************* * Print uchar string (regardless of utf) * *************************************************/ static void print_puchar(FILE *f, PCRE_PUCHAR ptr) { while (*ptr != '\0') { register pcre_uint32 c = *ptr++; if (PRINTABLE(c)) fprintf(f, "%c", c); else fprintf(f, "\\x{%x}", c); } } /************************************************* * Find Unicode property name * *************************************************/ static const char * get_ucpname(unsigned int ptype, unsigned int pvalue) { #ifdef SUPPORT_UCP int i; for (i = PRIV(utt_size) - 1; i >= 0; i--) { if (ptype == PRIV(utt)[i].type && pvalue == PRIV(utt)[i].value) break; } return (i >= 0)? PRIV(utt_names) + PRIV(utt)[i].name_offset : "??"; #else /* It gets harder and harder to shut off unwanted compiler warnings. */ ptype = ptype * pvalue; return (ptype == pvalue)? "??" : "??"; #endif } /************************************************* * Print Unicode property value * *************************************************/ /* "Normal" properties can be printed from tables. The PT_CLIST property is a pseudo-property that contains a pointer to a list of case-equivalent characters. This is used only when UCP support is available and UTF mode is selected. It should never occur otherwise, but just in case it does, have something ready to print. */ static void print_prop(FILE *f, pcre_uchar *code, const char *before, const char *after) { if (code[1] != PT_CLIST) { fprintf(f, "%s%s %s%s", before, priv_OP_names[*code], get_ucpname(code[1], code[2]), after); } else { const char *not = (*code == OP_PROP)? "" : "not "; #ifndef SUPPORT_UCP fprintf(f, "%s%sclist %d%s", before, not, code[2], after); #else const pcre_uint32 *p = PRIV(ucd_caseless_sets) + code[2]; fprintf (f, "%s%sclist", before, not); while (*p < NOTACHAR) fprintf(f, " %04x", *p++); fprintf(f, "%s", after); #endif } } /************************************************* * Print compiled regex * *************************************************/ /* Make this function work for a regex with integers either byte order. However, we assume that what we are passed is a compiled regex. The print_lengths flag controls whether offsets and lengths of items are printed. They can be turned off from pcretest so that automatic tests on bytecode can be written that do not depend on the value of LINK_SIZE. */ #ifdef PCRE_INCLUDED static /* Keep the following function as private. */ #endif #if defined COMPILE_PCRE8 void pcre_printint(pcre *external_re, FILE *f, BOOL print_lengths) #elif defined COMPILE_PCRE16 void pcre16_printint(pcre *external_re, FILE *f, BOOL print_lengths) #elif defined COMPILE_PCRE32 void pcre32_printint(pcre *external_re, FILE *f, BOOL print_lengths) #endif { REAL_PCRE *re = (REAL_PCRE *)external_re; pcre_uchar *codestart, *code; BOOL utf; unsigned int options = re->options; int offset = re->name_table_offset; int count = re->name_count; int size = re->name_entry_size; if (re->magic_number != MAGIC_NUMBER) { offset = ((offset << 8) & 0xff00) | ((offset >> 8) & 0xff); count = ((count << 8) & 0xff00) | ((count >> 8) & 0xff); size = ((size << 8) & 0xff00) | ((size >> 8) & 0xff); options = ((options << 24) & 0xff000000) | ((options << 8) & 0x00ff0000) | ((options >> 8) & 0x0000ff00) | ((options >> 24) & 0x000000ff); } code = codestart = (pcre_uchar *)re + offset + count * size; /* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */ utf = (options & PCRE_UTF8) != 0; for(;;) { pcre_uchar *ccode; const char *flag = " "; pcre_uint32 c; unsigned int extra = 0; if (print_lengths) fprintf(f, "%3d ", (int)(code - codestart)); else fprintf(f, " "); switch(*code) { /* ========================================================================== */ /* These cases are never obeyed. This is a fudge that causes a compile- time error if the vectors OP_names or OP_lengths, which are indexed by opcode, are not the correct length. It seems to be the only way to do such a check at compile time, as the sizeof() operator does not work in the C preprocessor. */ case OP_TABLE_LENGTH: case OP_TABLE_LENGTH + ((sizeof(priv_OP_names)/sizeof(const char *) == OP_TABLE_LENGTH) && (sizeof(priv_OP_lengths) == OP_TABLE_LENGTH)): break; /* ========================================================================== */ case OP_END: fprintf(f, " %s\n", priv_OP_names[*code]); fprintf(f, "------------------------------------------------------------------\n"); return; case OP_CHAR: fprintf(f, " "); do { code++; code += 1 + print_char(f, code, utf); } while (*code == OP_CHAR); fprintf(f, "\n"); continue; case OP_CHARI: fprintf(f, " /i "); do { code++; code += 1 + print_char(f, code, utf); } while (*code == OP_CHARI); fprintf(f, "\n"); continue; case OP_CBRA: case OP_CBRAPOS: case OP_SCBRA: case OP_SCBRAPOS: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s %d", priv_OP_names[*code], GET2(code, 1+LINK_SIZE)); break; case OP_BRA: case OP_BRAPOS: case OP_SBRA: case OP_SBRAPOS: case OP_KETRMAX: case OP_KETRMIN: case OP_KETRPOS: case OP_ALT: case OP_KET: case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: case OP_ONCE: case OP_ONCE_NC: case OP_COND: case OP_SCOND: case OP_REVERSE: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s", priv_OP_names[*code]); break; case OP_CLOSE: fprintf(f, " %s %d", priv_OP_names[*code], GET2(code, 1)); break; case OP_CREF: fprintf(f, "%3d %s", GET2(code,1), priv_OP_names[*code]); break; case OP_DNCREF: { pcre_uchar *entry = (pcre_uchar *)re + offset + (GET2(code, 1) * size) + IMM2_SIZE; fprintf(f, " %s Cond ref <", flag); print_puchar(f, entry); fprintf(f, ">%d", GET2(code, 1 + IMM2_SIZE)); } break; case OP_RREF: c = GET2(code, 1); if (c == RREF_ANY) fprintf(f, " Cond recurse any"); else fprintf(f, " Cond recurse %d", c); break; case OP_DNRREF: { pcre_uchar *entry = (pcre_uchar *)re + offset + (GET2(code, 1) * size) + IMM2_SIZE; fprintf(f, " %s Cond recurse <", flag); print_puchar(f, entry); fprintf(f, ">%d", GET2(code, 1 + IMM2_SIZE)); } break; case OP_DEF: fprintf(f, " Cond def"); break; case OP_STARI: case OP_MINSTARI: case OP_POSSTARI: case OP_PLUSI: case OP_MINPLUSI: case OP_POSPLUSI: case OP_QUERYI: case OP_MINQUERYI: case OP_POSQUERYI: flag = "/i"; /* Fall through */ case OP_STAR: case OP_MINSTAR: case OP_POSSTAR: case OP_PLUS: case OP_MINPLUS: case OP_POSPLUS: case OP_QUERY: case OP_MINQUERY: case OP_POSQUERY: case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPOSSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEPOSPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: case OP_TYPEPOSQUERY: fprintf(f, " %s ", flag); if (*code >= OP_TYPESTAR) { if (code[1] == OP_PROP || code[1] == OP_NOTPROP) { print_prop(f, code + 1, "", " "); extra = 2; } else fprintf(f, "%s", priv_OP_names[code[1]]); } else extra = print_char(f, code+1, utf); fprintf(f, "%s", priv_OP_names[*code]); break; case OP_EXACTI: case OP_UPTOI: case OP_MINUPTOI: case OP_POSUPTOI: flag = "/i"; /* Fall through */ case OP_EXACT: case OP_UPTO: case OP_MINUPTO: case OP_POSUPTO: fprintf(f, " %s ", flag); extra = print_char(f, code + 1 + IMM2_SIZE, utf); fprintf(f, "{"); if (*code != OP_EXACT && *code != OP_EXACTI) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_MINUPTO || *code == OP_MINUPTOI) fprintf(f, "?"); else if (*code == OP_POSUPTO || *code == OP_POSUPTOI) fprintf(f, "+"); break; case OP_TYPEEXACT: case OP_TYPEUPTO: case OP_TYPEMINUPTO: case OP_TYPEPOSUPTO: if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) { print_prop(f, code + IMM2_SIZE + 1, " ", " "); extra = 2; } else fprintf(f, " %s", priv_OP_names[code[1 + IMM2_SIZE]]); fprintf(f, "{"); if (*code != OP_TYPEEXACT) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_TYPEMINUPTO) fprintf(f, "?"); else if (*code == OP_TYPEPOSUPTO) fprintf(f, "+"); break; case OP_NOTI: flag = "/i"; /* Fall through */ case OP_NOT: fprintf(f, " %s [^", flag); extra = print_char(f, code + 1, utf); fprintf(f, "]"); break; case OP_NOTSTARI: case OP_NOTMINSTARI: case OP_NOTPOSSTARI: case OP_NOTPLUSI: case OP_NOTMINPLUSI: case OP_NOTPOSPLUSI: case OP_NOTQUERYI: case OP_NOTMINQUERYI: case OP_NOTPOSQUERYI: flag = "/i"; /* Fall through */ case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPOSSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTPOSPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: case OP_NOTPOSQUERY: fprintf(f, " %s [^", flag); extra = print_char(f, code + 1, utf); fprintf(f, "]%s", priv_OP_names[*code]); break; case OP_NOTEXACTI: case OP_NOTUPTOI: case OP_NOTMINUPTOI: case OP_NOTPOSUPTOI: flag = "/i"; /* Fall through */ case OP_NOTEXACT: case OP_NOTUPTO: case OP_NOTMINUPTO: case OP_NOTPOSUPTO: fprintf(f, " %s [^", flag); extra = print_char(f, code + 1 + IMM2_SIZE, utf); fprintf(f, "]{"); if (*code != OP_NOTEXACT && *code != OP_NOTEXACTI) fprintf(f, "0,"); fprintf(f, "%d}", GET2(code,1)); if (*code == OP_NOTMINUPTO || *code == OP_NOTMINUPTOI) fprintf(f, "?"); else if (*code == OP_NOTPOSUPTO || *code == OP_NOTPOSUPTOI) fprintf(f, "+"); break; case OP_RECURSE: if (print_lengths) fprintf(f, "%3d ", GET(code, 1)); else fprintf(f, " "); fprintf(f, "%s", priv_OP_names[*code]); break; case OP_REFI: flag = "/i"; /* Fall through */ case OP_REF: fprintf(f, " %s \\%d", flag, GET2(code,1)); ccode = code + priv_OP_lengths[*code]; goto CLASS_REF_REPEAT; case OP_DNREFI: flag = "/i"; /* Fall through */ case OP_DNREF: { pcre_uchar *entry = (pcre_uchar *)re + offset + (GET2(code, 1) * size) + IMM2_SIZE; fprintf(f, " %s \\k<", flag); print_puchar(f, entry); fprintf(f, ">%d", GET2(code, 1 + IMM2_SIZE)); } ccode = code + priv_OP_lengths[*code]; goto CLASS_REF_REPEAT; case OP_CALLOUT: fprintf(f, " %s %d %d %d", priv_OP_names[*code], code[1], GET(code,2), GET(code, 2 + LINK_SIZE)); break; case OP_PROP: case OP_NOTPROP: print_prop(f, code, " ", ""); break; /* OP_XCLASS cannot occur in 8-bit, non-UTF mode. However, there's no harm in having this code always here, and it makes it less messy without all those #ifdefs. */ case OP_CLASS: case OP_NCLASS: case OP_XCLASS: { int i; unsigned int min, max; BOOL printmap; BOOL invertmap = FALSE; pcre_uint8 *map; pcre_uint8 inverted_map[32]; fprintf(f, " ["); if (*code == OP_XCLASS) { extra = GET(code, 1); ccode = code + LINK_SIZE + 1; printmap = (*ccode & XCL_MAP) != 0; if ((*ccode & XCL_NOT) != 0) { invertmap = (*ccode & XCL_HASPROP) == 0; fprintf(f, "^"); } ccode++; } else { printmap = TRUE; ccode = code + 1; } /* Print a bit map */ if (printmap) { map = (pcre_uint8 *)ccode; if (invertmap) { for (i = 0; i < 32; i++) inverted_map[i] = ~map[i]; map = inverted_map; } for (i = 0; i < 256; i++) { if ((map[i/8] & (1 << (i&7))) != 0) { int j; for (j = i+1; j < 256; j++) if ((map[j/8] & (1 << (j&7))) == 0) break; if (i == '-' || i == ']') fprintf(f, "\\"); if (PRINTABLE(i)) fprintf(f, "%c", i); else fprintf(f, "\\x%02x", i); if (--j > i) { if (j != i + 1) fprintf(f, "-"); if (j == '-' || j == ']') fprintf(f, "\\"); if (PRINTABLE(j)) fprintf(f, "%c", j); else fprintf(f, "\\x%02x", j); } i = j; } } ccode += 32 / sizeof(pcre_uchar); } /* For an XCLASS there is always some additional data */ if (*code == OP_XCLASS) { pcre_uchar ch; while ((ch = *ccode++) != XCL_END) { BOOL not = FALSE; const char *notch = ""; switch(ch) { case XCL_NOTPROP: not = TRUE; notch = "^"; /* Fall through */ case XCL_PROP: { unsigned int ptype = *ccode++; unsigned int pvalue = *ccode++; switch(ptype) { case PT_PXGRAPH: fprintf(f, "[:%sgraph:]", notch); break; case PT_PXPRINT: fprintf(f, "[:%sprint:]", notch); break; case PT_PXPUNCT: fprintf(f, "[:%spunct:]", notch); break; default: fprintf(f, "\\%c{%s}", (not? 'P':'p'), get_ucpname(ptype, pvalue)); break; } } break; default: ccode += 1 + print_char(f, ccode, utf); if (ch == XCL_RANGE) { fprintf(f, "-"); ccode += 1 + print_char(f, ccode, utf); } break; } } } /* Indicate a non-UTF class which was created by negation */ fprintf(f, "]%s", (*code == OP_NCLASS)? " (neg)" : ""); /* Handle repeats after a class or a back reference */ CLASS_REF_REPEAT: switch(*ccode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: case OP_CRPOSSTAR: case OP_CRPOSPLUS: case OP_CRPOSQUERY: fprintf(f, "%s", priv_OP_names[*ccode]); extra += priv_OP_lengths[*ccode]; break; case OP_CRRANGE: case OP_CRMINRANGE: case OP_CRPOSRANGE: min = GET2(ccode,1); max = GET2(ccode,1 + IMM2_SIZE); if (max == 0) fprintf(f, "{%u,}", min); else fprintf(f, "{%u,%u}", min, max); if (*ccode == OP_CRMINRANGE) fprintf(f, "?"); else if (*ccode == OP_CRPOSRANGE) fprintf(f, "+"); extra += priv_OP_lengths[*ccode]; break; /* Do nothing if it's not a repeat; this code stops picky compilers warning about the lack of a default code path. */ default: break; } } break; case OP_MARK: case OP_PRUNE_ARG: case OP_SKIP_ARG: case OP_THEN_ARG: fprintf(f, " %s ", priv_OP_names[*code]); print_puchar(f, code + 2); extra += code[1]; break; case OP_THEN: fprintf(f, " %s", priv_OP_names[*code]); break; case OP_CIRCM: case OP_DOLLM: flag = "/m"; /* Fall through */ /* Anything else is just an item with no data, but possibly a flag. */ default: fprintf(f, " %s %s", flag, priv_OP_names[*code]); break; } code += priv_OP_lengths[*code] + extra; fprintf(f, "\n"); } } /* End of pcre_printint.src */
libgit2-main
deps/pcre/pcre_printint.c